*ARGS.TECH | BLOG | Linux `awk` Command Cheatsheet: Text Processing Made Easy
Loading...
BLOG
Linux `awk` Command Cheatsheet: Text Processing Made Easy
Terminal: ~

# Master the `awk` command with this practical cheatsheet.

# Learn to process text files, select columns,

# filter lines by patterns, and perform calculations in Linux.


# ----- Unleashing `awk`: A Practical Cheatsheet -----


# Print specific columns (fields) from a file or input:

# Fields are separated by spaces/tabs by default. $1=1st, $2=2nd, $0=whole line.

xinit@localhost:~$ ls -l | awk '{print $1, $9}'

# Prints permissions and filename.


# Print columns in a different order:

xinit@localhost:~$ cat /etc/passwd | awk -F: '{print $6, $1}'

# Prints home dir ($6) and username ($1), using ':' as delimiter.


# Use a custom Output Field Separator (OFS):

xinit@localhost:~$ awk -F: '{OFS=" -> "; print $1, $7}' /etc/passwd

# Prints username -> login_shell.


# ----- Filtering & Built-in Variables -----


# Print lines matching a pattern (like grep):

xinit@localhost:~$ awk '/error/ {print $0}' /var/log/syslog

# Prints lines containing 'error'.


# Print specific fields only for matching lines:

xinit@localhost:~$ awk '/Failed/ {print $1, $2, $9}' /var/log/auth.log

# Prints date, time, IP for failed logins.


# Use built-in variables: NR (Record Number) and NF (Number of Fields):

xinit@localhost:~$ awk '{print NR, NF, $0}' mydata.txt

# Prints line number, field count, and the line itself.


# Print lines with more than 5 fields:

xinit@localhost:~$ awk 'NF > 5 {print NR, $0}' mydata.txt


# ----- Advanced Tricks -----


# Perform calculations on columns (e.g., sum the sizes from `ls -l`):

# Note: This is a simplified example.

xinit@localhost:~$ ls -l | awk '{sum += $5} END {print "Total size:", sum}'


# Use BEGIN block to print a header before processing:

xinit@localhost:~$ awk 'BEGIN {print "User\tShell"} {OFS="\t"; print $1, $7}' /etc/passwd


# Use END block to print a summary after processing:

xinit@localhost:~$ awk '/Disconnected/ {count++} END {print count, "users disconnected."}' /var/log/auth.log

www.args.tech
Top button
© *ARGS.TECH
2025
v 2.25.0