A step by step introduction into the AWK command, it's syntax, uses and sample use cases.
The awk
command is a column based manipulation tool that can be used for a variety of things, from reading CSVs to killing processes, literally.
At the very core, AWK is based on the following
awk '{expression to qualify output} {print $output expression}'
Although it's a cli tool, it offers a lot of programming language paradigms such as
- Conditionals
- Loops
for more details on the awk command, the man
page is the best place to get familiar with it.
man awk
One good use case of the awk command is listing the users on a system. for this, we'll use the /etc/passwd
file
# The most basic command is simply to print all it received
cat /etc/passwd | awk '{print $0}'
# You can also specify a file separator using the -F flag
awk -F ":" '{print $0}' /etc/passwd
# You can also print out an optional output column separator
cat /etc/passwd | awk 'BEGIN{FS=":";OFS="-"} {print $NR $1,$7}'
Bonus points: try passing output into the uniq
command
df | awk '{print $2 + $3}'
# say you want to print a line only if the first column is greater than 3 characters
df | awk 'BEGIN{OFS="\t";} length($1) > 7 {print NR, $1}'
## You can decide to be more verbose, say print processes run by current user
ps aux | awk '{if($1 == "your_user_name_here") print $NF}'
## You can also handle regex matching per column, say i want to print the filesystems that start with /dev
df | awk '$1 ~ /^\/dev/ {print $1}'
## Or use the match operator
df | awk 'match(tolower($NF), /system/) {print $0}'
# Simple iterators
awk 'BEGIN{for (i=0; i <10; i++) print "The square of "i " = " i*i}'
# print processes 500 - 600
ps aux | awk 'NR==500, NR==600 {print NR $0}'
$NF : target the last column
NR : row numbwr
BEGIN: should happen before reading the file
END: should happen after reading the file
length(): gets the length
tolower(): to lower case