With the following input (test.txt
):
Sacramento California USA
Detroit Michigan USA
Vancouver BC Canada
By default, awk prints the current line on true conditions:
# Print only lines in USA
awk '$3 == "USA"' test.txt
Sacramento California USA
Detroit Michigan USA
Or perform a regex match:
awk '$3 ~ /[A-Z]{3}/' test.txt
Sacramento California USA
Detroit Michigan USA
To only print certain columns of matching lines:
# Print only city names in USA
awk '$3 == "USA" { print $1 }' test.txt
Sacramento
Detroit
-n
means do not print by default/p
command prints the matching line
Print entire matching line:
# Print only lines containing "USA"
sed -n -e '/USA/p' test.txt
Sacramento California USA
Detroit Michigan USA
Replace some of the text before printing only matching lines:
# Replace 'i' with 'x' on lines which contain USA
sed -n -e '/USA/s/i/x/gp' test.txt
Sacramento Calxfornxa USA
Detroxt Mxchxgan USA
sed -e '/USA/s/i/x/g' test.txt
Sacramento Calxfornxa USA
Detroxt Mxchxgan USA
Vancouver BC Canada
Notice the regex (
/USA/
) just precedes thes/
portion of a normalsed
replacement.
#bash #sed #awk #tips