Q & A Q & A Code

⨘ } awk miscellaneous commands

1. Extract pattern from file and do sum of all entries matching the pattern

grep ” Sequential ” idle_power.txt | awk ‘{sum += $3} END {print sum}’

Here $3 is which column is to get sum of. Idea is to grep a certain pattern from file from each line and then process output by awk to get sum of column 3.

idle_power.txt looks like this:

2.345E-6 3.45E-4 1.6078E-3 Sequential …
1.345E-6 2.45E-4 3.6078E-3 Sequential …

2. Count a pattern match – in this example Leprofesseur to be matched in file.txt

awk ‘/Leprofesseur/{sum++} END {print “Count = “, sum}’

3. Split line and then print – in this example split with “:” and print 5th column

awk ‘{split ($0, a, “:”); print a[5]}’

$0 – gets whole line, a – array contains split column value per line, : – separator for split, default is space.

4. Find a pattern from file, print certain columns, and sort the output

grep “Leprofesseur” file.txt | awk ‘{print $1, $2, $5}’ | sort | uniq -c

 569 total views,  5 views today

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.