Linux Command - awk

awk is often used to process text files.

Basic Ustage

Syntax

1
awk 'AWK COMMANDS' [FILE]

Awk defines variables for you to use. useful for extracting fields from the input

  • $0 - the whole line
  • $1 - the first field
  • $2 - the second field
  • $n - the nth field
  • $(NF-1) - field count -1
  • $NF - field count
  • NR - Retrieves total count of processed records

example

1
echo 'hello awk' | awk '{print $1}'

output

1
hello

You can specify the separator using -F option. To print the first field in /etc/password:

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

Sample output

1
2
3
4
5
6
7
8
9
root
daemon
bin
sys
sync
games
man
lp
......

To print count, the first and last field of the input field

1
awk -F ':' '{print NR " - " $1 " - " $(NF) }' /etc/passwd

Sample output

1
2
3
4
5
6
7
8
1 - root - /bin/bash
2 - daemon - /usr/sbin/nologin
3 - bin - /usr/sbin/nologin
4 - sys - /usr/sbin/nologin
5 - sync - /bin/sync
6 - games - /usr/sbin/nologin
7 - man - /usr/sbin/nologin
8 - lp - /usr/sbin/nologin

if Statement

1
awk -F ':' '{if ($1 < "g" ) print $1  }' /etc/passwd

This will print the names less than “g”

Sample output

1
2
3
daemon
bin
backup

If else statement

1
awk -F ':' '{if ($1 < "g" ) print $1; else print "---"  }' /etc/passwd

This will print the names less than “g”, else print “—“

Sample output

1
2
3
4
5
6
7
---
daemon
bin
---
---
---
---

Reference