How to use awk to print lines where a field matches a specific string?
In awk
:
awk '$2 == "LINUX" { print $0 }' test.txt
See awk
by Example for a good intro to awk
.
In sed
:
sed -n -e '/^[0-9][0-9]* LINUX/p' test.txt
See sed
by Example for a good intro to sed
.
My answer is very late, but no one has mentioned:
awk '$2~/LINUX/' file
This is a case in which you can use the beautiful idiomatic awk
:
awk '$2=="LINUX"' file
That is:
- The default action of
awk
when in a True condition is to print the current line. - Since
$2 == "LINUX"
is true whenever the 2nd field is LINUX, this will print those lines in which this happens.
In case you want to print all those lines matching LINUX
no matter if it is upper or lowercase, use toupper()
to capitalize them all:
awk 'toupper($2)=="LINUX"' file
Or IGNORECASE
with either of these syntaxs:
awk 'BEGIN {IGNORECASE=1} $2=="LINUX"' file
awk -v IGNORECASE=1 '$2=="LINUX"' file