shell script to print rows if there is a value in column 2
6,667
Using awk
(or its cousin gawk
):
gawk '$2==2 {print $0}' inputfile
In awk
columns are indicated by a $
, with $1
the first column, $2
the second, etc. The whole line is given by $0
. So this example reads: if column 2 is equal to 2, print the whole line.
Edit: as devnull said below:
gawk '$2==2' inputfile
is enough. To print the lines with 2 in the second column and 4 in the last use $NF
, which stands for the Number of Fields (i.e. the last column):
gawk '$2==2 && $NF==4' inputfile
Related videos on Youtube
Author by
Swish41
Updated on September 18, 2022Comments
-
Swish41 over 1 year
1 2 3 4 3 1 4 2 1 4 3 2 4 2 1 3
How can I print all rows, on which there is a 2 in the second column.
-
devnull over 10 years
{print $0}
is redundant here. You could simply sayawk '{$2==2}' inputfile
. -
Stéphane Chazelas over 10 years@devnull, ITYM
awk '$2==2'
orawk '$2=="2"'
if you want string comparison (not consider02
or2.0
as the same as2
).gawk
is more the grand-daughter ofawk
than its cousin ;-) -
devnull over 10 years@StephaneChazelas Right, it seems that the OP would want to quote
2
. -
Swish41 over 10 yearsis it possible to specify and ,if i want to print row with 2 in second column and 4 in last column.
-
devnull over 10 years@KevinParker Say
awk '$2=="2" && $NF=="4"' inputfile
-
Marek Zakrzewski over 10 yearsor
awk '$2 ~ /2/ && $NF ~ /'TEST'/ {print }'
filename -
terdon over 10 years@val0x00ff no, that will also print
foobar2barfoo
,~//
is a match operator and will be true for substrings. Also, you can't have nested'
, you'd have to use"
.