Posts

How to use AWK Command

Updated: Jul 29


Code

This article explains the command AWK, which is used in conjunction with the log check.



What is AWK Command?


When processing multiple lines of data separated by spaces or particular characters, this command can be used to output only the data in a particular column or to produce a total value.

awk'{print$[number of a row you want to extract];}'

For example, take a look at the following files.

test.txt
1 2 3 5
1 2 3 6
1 2 3 7
1 2 3 8

If you want only to display the first column, the output will look like the below.

cat test.txt | awk '{print$1;}'
1
1
1
1


How to use AWK Command


・To use any character as the delimiter

awk -F [Delimiter] '{print$1;}'

Ex) Only the 2 row is displayed

sed -e 's/ /:/g' test.txt | awk -F ':' '{print$2;}'
2
2
2
2


・To output line numbers

awk -F [Delimiter] '{print$1;}'

Ex) Only the 3 row is displayed

sed -e 's/ /:/g' test.txt | awk -F ':' '{print NR $3;}'
13
23
33
43

To make the result more readable, add a space between the numbers.

sed -e 's/ /:/g' test.txt | awk -F ':' '{print NR " " $3;}'
1 3
2 3
3 3
4 3



・To output a line where a particular column is a specific string

awk '$1==[Characters]'

Ex) Only displays a character 5 in row 4

sed -e 's/ /:/g' test.txt | awk -F ':' '$4=="5" {print NR " " $4;}'
1 5

Ex) In the reverse case

sed -e 's/ /:/g' test.txt | awk -F ':' '$4!="5" {print NR " " $4;}'
2 6
3 7
4 8



・To sum the numbers in a particular column

awk'{sum+=$1;}END{print sum;}'

Ex) Sum of the first line

sed -e 's/ /:/g' test.txt | awk -F ':' '{sum+=$1;}END{print sum;}'
4

Ex) Average

sed -e 's/ /:/g' test.txt | awk -F ':' '{sum+=$1;}END{print sum/NR;}'
1






This blog post is translated from a blog post written by Junichiro Okazaki our Japanese website Beyond Co..

14 views