How to use awk tool.

Hi all,

Today, through this post I am going to talk about some of the basics of the awk tool and real life case scenarios where this tool is very useful.

awk -F, '{sum+=NF} END {print sum}' <csv file> - Counts the total number of comma separated values in the csv file.

Awk command to calculate sum of floating point numbers in a column stored in a file.

awk '{sum+=sprintf("%f",$1)}END{printf "%.6f\n",sum}' <filename>
OR
LC_NUMERIC="C" awk '{sum += $1} END {print sum}' <filename>


How to add line numbers using awk command?

awk '{printf("%1d,%s\n", NR,$0)}' filename > filename_numbered

How to use awk to print from the 1st column to the last column?

awk '{out=""; for(i=2;i<=NF;i++){out=out" "$i}; print out}'


Print first few characters of a variable with awk?

 awk '{print substr($1,2,11)}' file

This will print second to 11th character in the variable $1.