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} '
![](https://www.allabouttechnologies.co.in/wp-content/uploads/2022/07/image.png)
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 }'
![](https://www.allabouttechnologies.co.in/wp-content/uploads/2022/07/image-1.png)
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) }'
![](https://www.allabouttechnologies.co.in/wp-content/uploads/2022/07/image-2.png)
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 }'
ORecho $v_dem | awk -F "|" ' {sum=0;for (i = 1; i <= NF; i++) if (i%2==0 ){sum+=$i} print sum }'
![](https://www.allabouttechnologies.co.in/wp-content/uploads/2022/07/image-3-1024x81.png)
![](https://www.allabouttechnologies.co.in/wp-content/uploads/2022/07/image-4-1024x79.png)
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 }'
![](https://www.allabouttechnologies.co.in/wp-content/uploads/2022/07/image-6.png)
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 }'
![](https://www.allabouttechnologies.co.in/wp-content/uploads/2022/07/image-5-1024x202.png)