I have the file "test.txt" that contains:
Val1 = '59'
Val2 = '76'
Val3 = '42'
Val4 = '53'I with this command:
perl -pe "s/^Val2 = '(.*)'/\1/" test.txtI Want:
76But I obtain:
Val1 = '59'
76
Val3 = '42'
Val4 = '53' 2 2 Answers
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.txtYou could also use a regex match rather than a regex substitute:
perl -lne "print \$1 if /^Val2 = '(.*)'/" test.txtor
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).
Use this Perl one-liner:
perl -lne "print for /^Val2\s+=\s+'(.*)'/" test.txtIt 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.
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