简体   繁体   中英

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

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

或内联替换:

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

作为单线:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM