Issue
I want to search 1st string 'abc' in each line of a file and if exists, search for 2nd string 'xyz' on the same matched line, then prepend 3rd string '//' at the beginning of matched line.
I tried below command, but it only prints output but does not make changes to existing file. Please help here.
grep 'abc' myfile | grep 'xyz' | sed 's/^/\/\//'
Solution
Use this Perl one-liner:
perl -i.bak -lpe 'm{abc} and m{xyz} and $_ = "//$_"; ' in_file
The Perl one-liner uses these command line flags:
-e
: Tells Perl to look for code in-line, instead of in a file.
-p
: Loop over the input one line at a time, assigning it to $_
by default. Add print $_
after each loop iteration.
-l
: Strip the input line separator ("\n"
on *NIX by default) before executing the code in-line, and append it when printing.
-i.bak
: Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak
. If you want to skip writing a backup file, just use -i
and skip the extension.
See also:
perldoc perlrun
: how to execute the Perl interpreter: command line switchesperldoc perlrequick
: Perl regular expressions quick startperldoc perlvar
: Perl predefined variables
Answered By - Timur Shtatland Answer Checked By - David Marino (WPSolving Volunteer)