Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use perl like sed?

Tags:

perl

I have a file that has some entries like

--ERROR--- Failed to execute the command with employee Name="shayam" Age="34"

--Successfully executed the command with employee Name="ram" Age="55"

--ERROR--- Failed to execute the command with employee Name="sam" Age="23"

--ERROR--- Failed to execute the command with employee Name="yam" Age="3"

I have to extract only the Name and Age of those for whom the command execution was failed. in this case i need to extract shayam 34 sam 23 yam 3. I need to do this in perl. thanks a lot..

like image 438
Raj Avatar asked Jul 01 '10 08:07

Raj


People also ask

What is sed in Perl?

The sed command is a stream editor that parses and performs basic text transformations on a file or an input stream from a pipeline. sed allows restricting the command to certain lines or characters.

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.


3 Answers

As a one-liner:

perl -lne '/^--ERROR---.*Name="(.*?)" Age="(.*?)"/ && print "$1 $2"' file
like image 85
Eugene Yarmash Avatar answered Nov 03 '22 21:11

Eugene Yarmash


Your title makes it not clear. Anyway...

while(<>) {
 next if !/^--ERROR/;
 /Name="([^"]+)"\s+Age="([^"]+)"/;
 print $1, "  ", $2, "\n";
}

can do it reading from stdin; of course, you can change the reading loop to anything else and the print with something to populate an hash or whatever according to your needs.

like image 37
ShinTakezou Avatar answered Nov 03 '22 21:11

ShinTakezou


perl -p -e 's/../../g' file

Or to inline replace:

perl -pi -e 's/../../g' file
like image 36
Nigel Benns Avatar answered Nov 03 '22 23:11

Nigel Benns