Thursday, October 16, 2008

AWK examples

Find number of columns in a pipe seperated csv file
awk -F"|" '{print NF}' vishnu.csv |uniq

Find sum of column of a pipe seperated csv file
awk -F"|" '{sum += $col } END { print sum }' vishnu.csv
awk -F"|" '{sum += $col } END { print sprintf("%.2f",sum) }' vishnu.csv (print float value)

Replace tab character with a pipe symbol in a csv file
awk '{gsub("\t","|");print}' vishnu.csv

print the 5th and 7th columns of csv file if 5th and 7th column values are not same
awk -F"," '{if($5 != $7) {print $5","$7}}' test.csv

print the line of csv file if 5th and 7th column values are same
awk -F"," '{if($5 !== $7) {print}}' test.csv

No comments: