Awk Examples

May 4, 2025

Awk Variables

  • NR: Number of records (rows) read so far.
  • NF: Number of fields (columns) in the current record (row).
  • IFS: Input field seperator.
  • OFS: Output field seperator.


Specify a different input field (column) separator.

The default input field separator is " ". A different field separator can be specified by using the -F option.

cat /etc/passwd | awk -F: '{print $1}'


Specify a different output field (column) separator.

The default output field separator is " ". A different field separator can be specified by using OFS. In the example below, $1=$1 forces awk to rebuild the entire record using the current value of OFS. See 1.

echo "All that is gold does not glitter" | awk '{OFS="-"; $1=$1; print $0}'
echo "All that is gold does not glitter" | awk -v OFS="-" '{$1=$1; print $0}'


Add a column, say the 5th column.

ls -l | awk 'BEGIN{sum=0}{sum += $5}END{print sum}'

The following also works because awk variables are automatically initialized to zero.

ls -l | awk '{sum += $5}END{print sum}'


Add a line number to every row.

Use the awk variable NR.

cat /etc/passwd | awk '{print NR, $0}'


Count the number of fields (columns) in each record.

Use the awk variable NF.

ls -l | awk '{print NF}'
cat /etc/passwd | awk -F: '{print NF}'


Print the last column.

Use the awk variable NF with a $ sign to dereference it.

ls -l | awk '{print $NF}'
cat /etc/passwd | awk -F: '{print $NF}'


Print the second last column.

Use the awk variable NF with a $ sign to dereference it.

ls -l | awk '{print $(NF-1)}'
cat /etc/passwd | awk -F: '{print $(NF-1)}'


Count the number of records (rows).

This is the same as wc -l.

cat /etc/passwd | awk 'END{print NR}'