How do I use perl like sed?

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

Answers


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.


As a one-liner:

perl -lne '/^--ERROR---.*Name="(.*?)" Age="(.*?)"/ && print "$1 $2"' file

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

or to inline replace:

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


As a one liner, try:

perl -ne 'print "$1 $2\n" if /^--ERROR/ && /Name="(.*?)"\s+Age="(.*?)"/;'

This is a lot like using sed, but with Perl syntax.


The immediate question of "how do I use perl like sed?" is best answered with s2p, the sed to perl converter. Given the command line, "sed $script", simply invoke "s2p $script" to generate a (typically unreadable) perl script that emulates sed for the given set of commands.


Refer to comments :

my @a = <>; # Reading entire file into an array
chomp @a;   # Removing extra spaces
@a = grep {/ERROR/} @a; # Removing lines that do not contain ERROR
# mapping with sed-like regexp to keep only names and ages :
@a = map {s/^.*Name=\"([a-z]+)\" Age=\"([0-9]+)\".*$/$1 $2/; $_} @a; 
print join " ",@a; # print of array content

Need Your Help

Root URl of the servlet

java java-ee

I want to get the root url of my web application from one of the servlet.