perl -lne "print for /^Val2\s+=\s+'(.*)'/" test.txt
It is slightly shorter and there is not need to escape any variables, since the for loop passes the captured group (.*) to print implicitly as $_, which is the default argument to print.
It also uses "\s+" (1 or more whitespace characters) instead of "" (1 blank) to be less strict about the input it accepts. While optional, I prefer to follow the rule about being less strict on the input, and more strict on the output (not sure about the source of this rule, though).
The Perl one-liner uses these command line flags: -e : Tells Perl to look for code in-line, instead of in a file. -n : Loop over the input one line at a time, assigning it to $_ by default. -l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
这个
-p
参数就像 sed 的默认打印 - 也像 sed,如果你想禁止默认打印,你可以使用-n
。所以你可以做
您还可以使用正则表达式匹配而不是正则表达式替代:
或者
(反斜杠是为了防止
$1
被 shell 扩展,因为表达式是在双引号中以允许在匹配中使用 Lieral 单引号)。使用这个 Perl 单行:
It is slightly shorter and there is not need to escape any variables, since the
for
loop passes the captured group(.*)
toprint
implicitly as$_
, which is the default argument toprint
.It also uses "
" (1 blank) to be less strict about the input it accepts. While optional, I prefer to follow the rule about being less strict on the input, and more strict on the output (not sure about the source of this rule, though).
\s+
" (1 or more whitespace characters) instead of "The Perl one-liner uses these command line flags:
-e
: Tells Perl to look for code in-line, instead of in a file.-n
: Loop over the input one line at a time, assigning it to$_
by default.-l
: Strip the input line separator ("\n"
on *NIX by default) before executing the code in-line, and append it when printing.SEE ALSO:
perldoc perlrun
: how to execute the Perl interpreter: command line switchesperldoc perlre
: Perl regular expressions (regexes)perldoc perlre
: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groupsperldoc perlrequick
: Perl regular expressions quick start