Hi,
I learned that in awk, $2 is the 2nd column. How to specify the ith line and the element at the ith row and jth column?
Thanks and regards!
Hi,
I learned that in awk, $2 is the 2nd column. How to specify the ith line and the element at the ith row and jth column?
Thanks and regards!
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}'
Edit: Here's an example with a header line and (redundant) field descriptions:
awk 'BEGIN {print "Name\t\tAge"} FNR == 5 {print "Name: "$3"\tAge: "$2}'
There are better ways to align columns than "\t\t" by the way.
To expand on Dennis's answer, use awk
's -v
option to pass the i
and j
values:
# print the j'th field of the i'th line
awk -v i=5 -v j=3 'FNR == i {print $j}'
To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:
awk '$2 ~ /abc/'
... and if you want to print only a particular column:
awk '$2 ~ /abc/ { print $3 }'
... and for a particular line number:
awk '$2 ~ /abc/ && FNR == 5 { print $3 }'