Select row and item in awk

I found out that in awk $ 2 is the second column. How to specify the i-th row and element in the i-th row and j-th column?

+41
awk
01 Oct '09 at 21:12
source share
5 answers

To print the second line:

awk 'FNR == 2 {print}' 

To print the second field:

 awk '{print $2}' 

To print the third field of the fifth line:

 awk 'FNR == 5 {print $3}' 

Change Here is an example with a row heading and a (redundant) field description:

 awk 'BEGIN {print "Name\t\tAge"} FNR == 5 {print "Name: "$3"\tAge: "$2}' 

There are more efficient ways to align columns than "\ t \ t".

+101
Oct 01 '09 at 21:25
source share

To print columns with a specific row, you use the // search pattern. For example, if you are looking for a second column containing abc:

 awk '$2 ~ /abc/' 

... and if you want to print only a specific column:

 awk '$2 ~ /abc/ { print $3 }' 

... and for a specific line number:

 awk '$2 ~ /abc/ && FNR == 5 { print $3 }' 
+24
02 Oct '09 at 22:39
source share

To extend Dennis's answer, use the awk -v option to pass the values ​​of i and j :

 # print the j'th field of the i'th line awk -vi=5 -vj=3 'FNR == i {print $j}' 
+21
Oct 02 '09 at 3:13
source share

Since awk and perl are closely related ...




Perl equivalents of @ Dennis awk solutions:

To print the second line:
perl -ne 'print if $. == 2' file

To print the second field:
perl -lane 'print $F[1]' file

To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file




Perl equivalent of @Glenn solution:

Printing the j-th field of the i-th row

perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file




@Hai Pearl Equivalents:

if you are looking for a second column containing abc:

perl -lane 'print if $F[1] =~ /abc/' foo

... and if you want to print only a specific column:

perl -lane 'print $F[2] if $F[1] =~ /abc/' foo

... and for a specific line number:

perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo




-l removes newline characters and adds them back when printing -a autosplits the input line to the @F array, using a space as a separator -n loop over each line of the input file
-e execute code inside quotes
$F[1] is the second element of the array, since Perl starts at 0
$. - line number

0
Nov 03 '15 at 0:03
source share

I found this working team

root @gateway: / home / sshuser # aws ec2 describe-instances -instance-ids i-2db0459d | grep 'STATE \ | TAG '| awk 'FNR == 1 {print $ 1}'

STATE

0
Jul 27 '16 at 5:23
source share



All Articles