awk

All posts tagged awk

Sometimes you need to get a specified column of a text but it’s really hard to choose a suitable column separator. For example we will get the second column from the following text file.

$ cat ./text.txt
abc,def-ghi
123-456-789
qaz,wsx,edc
qwe-asd,zxc

We can see two field separators: a comma and a minus sign. Fortunately awk can use regular expressions as field separator. In this case we use the following line.

$ awk -F"[-,]" '{print $2}' ./text.txt 
def
456
wsx
asd

 

The Awk tool has a several build-in variables which allow to navigate through a fields of processing text. One of them is a NF. A value of this variable is a number of fields in a current line. This simple example shows how useful is this variable when we don’t know how much columns has the input file.

This is a contents of our testing text file:

$ cat ./file.txt
abc     def     ghi
123     456     789
jkl     mno
321     654

Continue Reading