Examples of Awk Command

In this blog, I will explain various situations where you can use AWK command.
Scenario 1: Identify the occurrence of a particular delimiter present in a variable.
For example , consider a variable v_dem=”v1|100|v2|200|v3|300″
Use Awk command , you can easily find the occurrence of Pipe delimiter in v_dem variable. Here, NF stands for Number of fields .
LINUX COMMAND : echo $v_dem |awk -F '|' '{print NF} '

Scenario 2: Print the values separated by Delimiter(Pipe in this case) using AWK command.
LINUX COMMAND : echo $v_dem | awk -F "|" ' {for (i = 1; i <= NF; i++) print "Value of " i " is " $i }'

Scenario 3: Print the values in key-value pair separated by Delimiter (Pipe in this case) using AWK command

LINUX COMMAND : echo $v_dem | awk -F "|" ' {for (i = 1; i <= NF; i++) if (i==1 || i==3 || i==5) print "Value of " $i ":" $(i+1) }'

Scenario 4: Print the sum of all numeric values separated by Delimiter (Pipe in this case) using AWK command.

LINUX COMMAND : echo $v_dem | awk -F "|" ' {sum=0;for (i = 1; i <= NF; i++) if (i==2 || i==4 || i==6){sum+=$i} print sum }'

OR
echo $v_dem | awk -F "|" ' {sum=0;for (i = 1; i <= NF; i++) if (i%2==0 ){sum+=$i} print sum }'

Here, If you noticed, sum function is performed on even positions as it is clear from variable v_dem value. There is another way to calculate numeric values . Check if value is having only 0 to 9 characters or not , if yes, then sum those values.
echo $v_dem | awk -F "|" ' {sum=0;for (i = 1; i <= NF; i++) if ( $i ~ /^[0-9]+$/) {sum+=$i} print sum }'



Scenario 5: Print the values separated by Delimiter (Pipe in this case) present at either odd or even positions using AWK command.

LINUX COMMAND : echo $v_dem | awk -F "|" ' {sum=0;for (i = 1; i <= NF; i++) if (i%2==0 ) print "The value at Position " i "- " $i }'

echo $v_dem | awk -F "|" ' {sum=0;for (i = 1; i <= NF; i++) if (i%2==1 ) print "The value at Position " i "- " $i }'

Related posts