1752770 Members
5053 Online
108789 Solutions
New Discussion юеВ

parser multiple lines

 
SOLVED
Go to solution
Gemini_2
Regular Advisor

parser multiple lines

I have a file like this

*******************************************
Unix ID:XXX
Total Views:5
content....
*******************************************
Unix ID:YYY
Total Views:12
content....
********************************************
...


I want to find whose view is greater than 10 and extract his data.

For example above, the output should look like

Unix ID:YYY
Total Views:12
content....

can awk or whatever..take multiple lines?

thank you

5 REPLIES 5
Hein van den Heuvel
Honored Contributor
Solution

Re: parser multiple lines

There are several prior advice in the ITRC forum about 'grepping fr paragraphs' and the likes. Check those out!
Google: +awk +paragraph +site:itrc.hp.com

Here is how I might solve your question with a '1 liner'.

awk '/Total V/{split($0,a,":"); if (a[2] >10) {print unix}} /^\*/{a[2]=0} {if(a[2]>10){print} else {unix=$0}}' x


In details:

==> /Total V/{split($0,a,":");
If we see the line beginning with total then split using a colon or get the number in array element a[2].

==> if (a[2] >10) {print unix}}
If that array element is larger than 10, print a stashed away prior line(s).

==> /^\*/{a[2]=0}
If we see line starting with *, then indicate being done by clearing the counter.

==> {if(a[2]>10){print} else {unix=$0}}
For every line, print it if count is high, else stash away line in case it happens to become next "Unix ID"


Good luck,
Hein.
Sandman!
Honored Contributor

Re: parser multiple lines

Hi,

You can use the awk construct given below. :

==============mycmds.awk=====================
$0 ~ /^Unix ID/ {
prev=$0
getline
val=z[split($NF,z,":")]
curr=$0
getline
if(val>10) {
printf("%s\n%s\n%s\n",prev,curr,$0) }
}
=============================================

Put all the above commands in a file named mycmds.awk and execute as:

# awk -f mycmds.awk

cheers!
James R. Ferguson
Acclaimed Contributor

Re: parser multiple lines

Hi:

This would work for you:

#!/usr/bin/perl
while (<>) {
print if $tog == 1;
$tog = 0 if m/^\*/;
next if ($id = m/Unix/);
if (m/Total Views:(\d+)/) {
if ($1 > 10) {
$tog = 1;
print $id, $_ ;
}
}
}

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: parser multiple lines

Hi (again):

Oh, and having named my script:

# parse.pl
#!/usr/bin/perl
while (<>) {
print if $tog == 1;
$tog = 0 if m/^\*/;
next if ($id = m/Unix/);
if (m/Total Views:(\d+)/) {
if ($1 > 10) {
$tog = 1;
print $id, $_ ;
}
}
}

...run as:

./parse.pl filename

Regards!

...JRF,,,
Gemini_2
Regular Advisor

Re: parser multiple lines

thanks everyone for your suggestions.

let me give a try!

I assigned everyone some points!!