2
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.

1 Answer 1

8

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
7
  • 1
    {print $0} is redundant here. You could simply say awk '{$2==2}' inputfile.
    – devnull
    Oct 8, 2013 at 9:22
  • 2
    @devnull, ITYM awk '$2==2' or awk '$2=="2"' if you want string comparison (not consider 02 or 2.0 as the same as 2). gawk is more the grand-daughter of awk than its cousin ;-) Oct 8, 2013 at 9:25
  • @StephaneChazelas Right, it seems that the OP would want to quote 2.
    – devnull
    Oct 8, 2013 at 9:28
  • is it possible to specify and ,if i want to print row with 2 in second column and 4 in last column. Oct 8, 2013 at 9:39
  • 1
    @KevinParker Say awk '$2=="2" && $NF=="4"' inputfile
    – devnull
    Oct 8, 2013 at 9:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .