The -p argument is like sed's default print - also like sed, if you want to suppress default print, you would use -n instead.
So you could do
perl -ne "print if s/^Val2 = '(.*)'/\1/" test.txt
You could also use a regex match rather than a regex substitute:
perl -lne "print \$1 if /^Val2 = '(.*)'/" test.txt
or
perl -nE "say \$1 if /^Val2 = '(.*)'/" test.txt
(the backslash is to protect $1 from being expanded by the shell, since the expression is in double quotes to allow use of lieral single quotes in the match).
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.
The
-p
argument is like sed's default print - also like sed, if you want to suppress default print, you would use-n
instead.So you could do
You could also use a regex match rather than a regex substitute:
or
(the backslash is to protect
$1
from being expanded by the shell, since the expression is in double quotes to allow use of lieral single quotes in the match).Use this Perl one-liner:
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