How to use perl as sed?

I have a file with several elements, for example

--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 need to extract only the name and age of those for whom the command has been executed. in this case I need to extract shayam 34 sam 23 yam 3. I need to do this in perl. Many thanks.

+3
source share
6 answers

Your name makes this incomprehensible. Anyway...

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

can do this with stdin; Of course, you can change the reading cycle to something else and print something to fill the hash or something according to your needs.

+6
source

As single line:

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

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

inline replace:

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

+9

, :

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

sed, Perl.

+5

Direct question: "How to use perl, for example sed?" It is best to answer s2p, sed to a perl converter. Given the command line "sed $ script", just call "s2p $ script" to create a (usually unreadable) perl script that emulates sed for a given set of commands.

+2
source

Refer to the 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
-2
source

Source: https://habr.com/ru/post/1752591/


All Articles