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
Share:
6,667

Related videos on Youtube

Swish41
Author by

Swish41

Updated on September 18, 2022

Comments

  • Swish41
    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
    devnull over 10 years
    {print $0} is redundant here. You could simply say awk '{$2==2}' inputfile.
  • Stéphane Chazelas
    Stéphane Chazelas over 10 years
    @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 ;-)
  • devnull
    devnull over 10 years
    @StephaneChazelas Right, it seems that the OP would want to quote 2.
  • Swish41
    Swish41 over 10 years
    is it possible to specify and ,if i want to print row with 2 in second column and 4 in last column.
  • devnull
    devnull over 10 years
    @KevinParker Say awk '$2=="2" && $NF=="4"' inputfile
  • Marek Zakrzewski
    Marek Zakrzewski over 10 years
    or awk '$2 ~ /2/ && $NF ~ /'TEST'/ {print }' filename
  • terdon
    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 ".