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?
chomp (my @lineNumbers=`grep -n "textToFind" $fileToProcess | sed -n 's/^\([0-9]*\)[:].*/\1/p'`)
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.)
Perl supports every feature sed does and has its own set of extended regular expressions, which give it extensive power in pattern matching and processing.
Performing a regex search-and-replace is just as easy: $string =~ s/regex/replacement/g; I added a “g” after the last forward slash. The “g” stands for “global”, which tells Perl to replace all matches, and not just the first one.
Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.
Use power Luke:
$ echo -e "a\nb\na"|perl -lne'/a/&&print$.'
1
3
Thus when you want same think as this slow and overcomplicated grep
and sed
combination you can do it far simpler and faster in perl itself:
my @linenumbers;
open my $fh, '<', $fileToProcess or die "Can't open $fileToProcess: $!";
while (<$fh>)
{
/textToFind/ and push @lineNumbers, $.;
}
close $fh;
Or with same memory culprits as the original solution
my @linenumbers = do {
open my $fh, '<', $fileToProcess or die "Can't open $fileToProcess: $!";
my $i;
map { ( ++$i ) x /textToFind/ } <$fh>
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With