在这种情况下,Perl 可以轻松地充当您的朋友。您可以将整个文件读入内存以在多行上应用正则表达式。将输入记录分隔符设置为0777
会导致这种“啜饮”动作。开关只是说读取命令行上提供的-n
一个或多个文件。开关的-e
参数构成要执行的代码。
正则表达式的/s
修饰符允许.
匹配换行符。\m
修饰符允许^
和在$
嵌入换行符之前和之后立即匹配。这些是解析包含多个逻辑行的字符串的关键。修饰符告诉正/g
则表达式引擎全局搜索所有匹配项。
perl -0777 -ne 'print "$1 $2\n" while m{^(\S+).+?\[age=(\d+)\]}gms' file
给定这样的输入文件:
01238584 (other info) more info, more info
[age=81][otherinfo][etc, etc]
98765432 (still other info) still more info, and more info
[age=82][and more otherinfo][etc, etc, ad infinitum]
...上面的脚本输出:
01238584 81
98765432 82
我们可以这样剖析正则表达式:
perl -MYAPE::Regex::Explain -e 'print YAPE::Regex::Explain->new(qr/m{^(\S+).
+?[age=(\d+)]}gms/)->explain()'
The regular expression:
(?-imsx:m{^(\S+).+?\[age=(\d+)\]}gms)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
m{ 'm{'
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
\S+ non-whitespace (all but \n, \r, \t, \f,
and " ") (1 or more times (matching the
most amount possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
.+? any character except \n (1 or more times
(matching the least amount possible))
----------------------------------------------------------------------
\[ '['
----------------------------------------------------------------------
age= 'age='
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
\] ']'
----------------------------------------------------------------------
}gms '}gms'
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------