Skip to content

awk

awk: scripting language to manipulate text

example text file (with turtle name, banner-color, personality), tmnt.txt:

leonardo blue leader
raphael red hothead
michelangelo orange party-animal
donatello purple geek

awk as default sees spaces as delimiters for fields.

example, print everything:
awk '{print}' tmnt.txt
or (0 represents the entire file),
awk '{print $0}' tmnt.txt

example, show specific (first) field only:
awk '{print $1}' tmnt.txt

example, show specific (third) field only:
awk '{print $3}' tmnt.txt

example, print multiple fields (1 and 3):
awk '{print $1,$3}' tmnt.txt

chaining commands into awk:
ls -l | awk '{print $1}'

example:
echo "Hello from code-vault" | awk '{print $1,$3}'

example: getting last field using number of fields NF (in this case 3):
awk '{print $NF}' tmnt.txt

example: no space delimiters
this won't work:
awk '{print $2}' /etc/passwd
because, e.g.:
cat /etc/passwd | grep gus
instead, set a different field separator, F:
awk -F':' '{print $2}' /etc/passwd

to find out which shell each user of the system is using,
awk -F':' '{print $1,$7}' /etc/passwd