AWK Programming Notes
expand_circle_rightAwk is a programming language that can handle and manipulate data. Suppose we have the following data file.
datafile.txt
orange 22.5 0
banana 19.5 12
apple 23.0 0
mango 25.0 30
papaya 22.5 25Print only certain field, first field for instance.
~
awk '{print $1}' datafile.txtPrint the lines (the whole line, $0) with value at third field is greater than 0.
~
awk '$3 > 0 {print $0}' datafile.txtDo some maths (value at second field is multiplied by value at third field) and print.
~
awk '$3 > 0 {print $1, $2 * $3}' datafile.txtPrint only the lines with value at third field is equal to 0.
~
awk '$3 == 0 {print $0}' datafile.txtPrint the line that matches given pattern.
~
awk '/apple/ {print $0}' datafile.txtPrint the line that certain field matches given pattern, exact match and regex match.
~
awk '$1 == "apple" {print $0}' datafile.txt~
awk '$1 ~ /apple/ {print $0}' datafile.txtPassing variable and matching, and print.
~
fruit="apple"
awk -v f=$fruit '$0 ~ f {print $0}' datafile.txt~
fruit="apple"
awk -v f=$fruit '$1 ~ f {print $0}' datafile.txt