I know how to use sed
with grep
, but within Perl the below fails. How can one get sed
to work within a Perl program?
c
It is easier to use Perl than to use grep and sed; see another answer.
Your code failed because Perl messed with the backslashes in your sed code. To prevent this, write your sed code in 'a single-quoted Perl string'
, then use \Q$sedCode\E
to interpolate the code into the shell command. (About \Q...E
, see perldoc -f quotemeta. Its usual purpose is to quote characters for regular expressions, but it also works with shell commands.)
my $fileToProcess = "example.txt";
my $sedCode = 's/^\([0-9]*\)[:].*/\1/p';
chomp(my @linenumbers =
`grep -n "textToFind" \Q$fileToProcess\E | sed -n \Q$sedCode\E`);
printf "%s\n", join(', ', @linenumbers);
Given example.txt
with
this has textToFind
this doesn't
textToFind again
textNotToFind
the output is 1, 3
.