Some useful and quick awk scripts

 

How to print the total of a column such as total disk space utilization from df -k

df -k | grep -v Filesystem | awk '{ SUM += $3} END { print SUM/1024 }'

 

Substitute "yes" with "no" on each line

awk '{sub(/yes/,"no");print}'           # replaces only 1st instance
gawk '{$0=gensub(/yes/,"no",5);print}'  # replaces only 5th instance
awk '{gsub(/yes/,"no");print}'          # replaces all instances in a line

 

Substitute "yes" with "no" only for lines which contain "hat"

awk '/hat/{gsub(/yes/, "no")};{print}'

 

Substitute "yes" with "no" except for lines which contain "hat"

awk '!/hat/{gsub(/yes/, "no")};{print}'

 

Change "honey" or "sugar" or "jam" to "sweet"

awk '{gsub(/honey|sugar|jam/, "sweet"); print}'