Skip to content

Instantly share code, notes, and snippets.

@nullstream
Created April 14, 2018 13:59
Show Gist options
  • Save nullstream/cbdb32fb057fd8748bf4ecb4b2bf920e to your computer and use it in GitHub Desktop.
Save nullstream/cbdb32fb057fd8748bf4ecb4b2bf920e to your computer and use it in GitHub Desktop.
2 Minute Guide to awk.
awk '{ print $1 }' file.txt # Print column one from each line in file.txt
cat file.txt | awk '{print $2}' # Print column two from each line of piped input.
awk '{ print $3 $5 $NF }' file.txt # Print columns 3 & 5 and number of colums/fields on each line of file.txt.
awk 'BEGIN{ s=0 } { s+= $3 } END{ print s }' file.txt # Sum up column 3 and print at the end of input (BEGIN=pre input, END=EOF)
awk 'BEGIN{n=0}{n+=$NF}END{print n/$NR}' file.txt # Print the average number of of fields per record in file.txt
awk '/foo/' file.txt # Print lines that contain 'foo' in file.txt
awk '/foo/{print $0}' file.txt # Print all records on lines that contain 'foo' in file.txt
awk '/foo/{print $2}' file.txt # Print column 2 from all lines that contain 'foo' in file.txt
awk '$2=="foo"{print $1}' file.txt # Print column 1 from all lines that contain 'foo' in column $2 in file.txt
awk -F\; '{print $5}' file.txt # Print column 5 from all lines in file.txt DELIMITED by semicolon(;) [ie. CSV]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment