Archive

Posts Tagged ‘AWK’

Print next few lines after pattern in AWK

May 6, 2010 1 comment

Input data.txt is a collection report for XYZ corp group by different collection zones.

$ cat data.txt
Total Collection = $10291 {Fri May  8}
zone7   4500
zone8   3545
zone1   1200
zone0   900
zone3   70
zone5   67
zone11  9
Total Collection = $11847 {Sat May  9}
zone1   2800
zone3   2800
zone6   2567
zone8   2300
zone9   1200
zone12  90
zone11  90

Required: We need to find out the top 4 collection zones for each day from the above file. i.e. to print next 4 lines where the pattern “Total Collection =” is found (as the items are sorted on collection amount).

This is how we can achieve this using awk:

$ awk '/^Total Collection =/{c=4;next}c-->0' data.txt
zone7   4500
zone8   3545
zone1   1200
zone0   900
zone1   2800
zone3   2800
zone6   2567
zone8   2300

Now if we need to print the header line also, something like:

$ awk '/^Total Collection =/{c=4;{print}next}c-->0' data.txt
Total Collection = $10291 {Fri May  8}
zone7   4500
zone8   3545
zone1   1200
zone0   900
Total Collection = $11847 {Sat May  9}
zone1   2800
zone3   2800
zone6   2567
zone8   2300

And if you want to just print the date part as the header with top 4 collection zones.

$ awk -F "[{,}]" '/^Total Collection =/{c=4;{print $2}next}c-->0' data.txt
Fri May  8
zone7   4500
zone8   3545
zone1   1200
zone0   900
Sat May  9
zone1   2800
zone3   2800
zone6   2567
zone8   2300
Categories: Linux / Unix, Tutorial Tags: , , ,

Multiple FS in AWK

May 6, 2010 1 comment

Sample file:

$ cat summary.txt
A|Jan|clerk|02:45
B|Jan|Salesman|02:12
C|Jan|Accountant|03:12
A|Feb|clerk|01:10
B|Feb|Salesman|11:10
B|March|Salesman|3:10
C|Feb|Accountant|3:34

Output Required:

(First field)|(last field converted to minutes)
i.e.
A|165
B|132
C|192
A|70
B|670
B|190
C|214

This is how we can specify two field separators (| and 🙂 with FS in awk:

$ awk 'BEGIN{FS="[|,:]"; OFS="|"} {print $1,$(NF-1)*60+$NF}' summary.txt
Categories: Linux / Unix, Tutorial Tags: , ,
%d bloggers like this: