Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use sed from Perl?

Tags:

sed

perl

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'`)
like image 879
Alex Wong Avatar asked Mar 04 '09 16:03

Alex Wong


People also ask

How to use sed in perl?

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

Can sed use Perl regex?

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.

How do I search and replace in Perl?

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.

How do you use sed substitution?

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.


1 Answers

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>
};
like image 86
Hynek -Pichi- Vychodil Avatar answered Dec 07 '22 23:12

Hynek -Pichi- Vychodil