bash --> perl command: print only the replaced text

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.txt

I Want:

76

But 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.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).

2

Use this Perl one-liner:

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.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlre: Perl regular expressions (regexes)
perldoc perlre: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups
perldoc perlrequick: Perl regular expressions quick start

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like