Tuesday, April 10, 2012

Count the number of occurances of a pattern in a file using awk

awk '{ for (i=1;i<=NF;i++) if ( $i == "word" ) count++ } END{print count}' filename

This will print the count of the occurance of  a pattern "word" in a file.

Friday, April 6, 2012

How to compare the values of a column in awk in a same file and consecutive lines..


If one would like to compare the values of 2nd column of consecutive lines of same file in such a way so that if the difference between first value and second value is more than 100 it should print complete line else ignore line.

Input File:
=======

ABC 2500
ABCD 123
XYZ 122
WXYZ 2565


Desired Output:
==========

ABC 2500 (i.e. difference between 2500 and 123 is greater than 100 here)
XYZ 122 (i.e. difference between 122 and 2565 is greater than 100 here)

Command:
=======

awk 'NR % 2 != 0 {a=$1; b=$2} NR % 2 == 0 {if (b - $2 > 100 || $2 - b > 100){print a,b}}' inputfile
 

Blogger news

Blogroll