Awk /

Usage

Source: Learning Awk Is Essential For Linux Users - Invidious

Usage

awk can be used to extract and manipulate fields in text. This command is particularly useful when information is presented in columns.

Use

awk is used as follows:

$ awk '{instructions'} file

Options

-F

Change column delimiter

Instructions

print

Prints a field. Fields are named $i, $0 being the entire line and $1 the element corresponding to the first column in each line.

  $ echo “1 2 3 abc” | awk '{print $0}'
  $ echo “1 2 3 abc” | awk '{print $1}'
  $ echo “1 2 3 abc” | awk '{print $2}'

Searching for an expression

awk can apply a command after a filter. The filter is defined between //.

  $ echo “””
            abc 1 2 3
            def 4 5 6
                ““”| awk '/a/ {print $2 “+” $3 “=” $2+$3}'

Keywords

NF

NF (Number of Fields) is a variable containing the number of columns in the row. $NF is used to obtain the value of the last field in the row.

  $ echo “A 2 3 4 9” | awk '{print NF}'
  $ echo “A 2 3 4 9” | awk '{print $NF}'

NR

NR (Number of Records) is a variable containing the number of lines in the file. $NR is used to obtain the value of the last line.

FS

FS (Field Separator) defines the column separator.

OFS

OFS (Output Field Separator) defines the output field separator.

   $ echo “A-2-3-4-9” | awk -F “-” -v OFS='/' '{print $1,$2}'

BEGIN

BEGIN is used to define a set of instructions that will be performed before the first line is read.

END

END allows you to define a set of instructions to be performed after the last line has been read.

   $ echo “1 2 3 abc” | awk 'BEGIN{print “this is the title”} {print $4} END{print “this is the end”}'