Now that you are familiar with basic awksyntax and regular expressions, this chapter will dive deep into field processing. You'll learn how to set input and output field separators, how to use regexps for defining fields and how to work with fixed length fields.
As seen earlier, awk automatically splits input into fields which are accessible using $N where N is the field number you need. You can also pass an expression instead of numeric literal to specify the field required.
$ cat table.txt brown bread mat hair 42 blue cake mug shirt -7 yellow banana window shoes 3.14 $ # print fourth field if first field starts with 'b' $ awk '$1 ~ /^b/{print $4}' table.txt hair shirt $ # print the field as specified by value stored in 'f' variable $ awk -v f=3 '{print $f}' table.txt mat mug window
The NF special variable will give you the number of fields for each input line. This is useful when you don't know how many fields are present in the input and you need to specify field number from the end.
$ # print the last field of each input line $ awk '{print $NF}' table.txt 42 -7 3.14 $ # print the last but one field $ awk '{print $(NF-1)}' table.txt hair shirt shoes $ # don't forget the parentheses! $ awk '{print $NF-1}' table.txt 41 -8 2.14
By default, awk does more than split the input on spaces. It splits based on one or more sequence of space or tab or newline characters. In addition, any of these three characters at the start or end of input gets trimmed and won't be part of field contents. Input containing newline character will be covered in Record separators chapter.
$ echo ' a b c ' | awk '{print NF}' 3 $ # note that leading spaces isn't part of field content $ echo ' a b c ' | awk '{print $1}' a $ # note that trailing spaces isn't part of field content $ echo ' a b c ' | awk '{print $NF "."}' c. $ # here's another example with tab characters thrown in $ printf ' one \t two\t\t\tthree ' | awk '{print NF}' 3 $ printf ' one \t two\t\t\tthree ' | awk '{print $2 "."}' two.
When passing an expression for field number, floating-point result is acceptable too. The fractional portion is ignored. However, as precision is limited, it could result in rounding instead of truncation.