Print only the lines that match a regular expression “/regex/” (emulates “grep”).
1
cat file | awk '/regex/'
Print only the lines that do not match a regular expression “/regex/” (emulates “grep -v”).
1
cat file | awk '!/regex/'
Print the line immediately before a line that matches “/regex/” (but not the line that matches itself).
1
cat file | awk '/regex/ { print x }; { x=$0 }'
Print the line immediately after a line that matches “/regex/” (but not the line that matches itself).
1
cat file | awk '/regex/ { getline; print }'
Print lines that match any of “AAA” or “BBB”, or “CCC”.
1
cat file | awk '/AAA|BBB|CCC/'
Print lines that contain “AAA” and “BBB”, and “CCC” in this order.
1
cat file | awk '/AAA.*BBB.*CCC/'
Print only the lines that are 65 characters in length or longer.
1
cat file | awk 'length > 64'
Print a section of file from regular expression to end of file.
1
cat file | awk '/regex/,0'
Print lines 8 to 12 (inclusive).
1
cat file | awk 'NR==8,NR==12'
Print line number 52.
1
cat file | awk 'NR==52'
Print section of a file between two regular expressions (inclusive).
1
cat file | awk '/Iowa/,/Montana/'
Delete all blank lines from a file.
1
cat file | awk NF
This one-liner uses the special NF variable that contains number of fields on the line. For empty lines, NF is 0, that evaluates to false, and false statements do not get the line printed.
Create a string of a specific length (generate a string of x’s of length 513).
1
awk 'BEGIN { while (a++<513) s=s "x"; print s }'
Insert a string of specific length at a certain character position (insert 49 x’s after 6th char).