I want to do a regex find & replace on a file on the command line with complicated regex, so I need PCRE's & am using perl -pe "s/foo/bar"
(rather than sed
), that prints out all lines after applying the s///
, but it also prints lines that don't match.
Is there a perl
command line one-liner which will not print lines that don't match? I know of perl -pe s/foo/bar/ if /foo/
, but then I need to duplicate the regex. Is it possible without repeating myself?
You can use -n
flag (which, unlike -p
, does not automatically print all lines) and print only lines which match the regex:
perl -ne 's/foo/bar/ && print'
Or, equivalently:
perl -ne 'print if s/foo/bar/'