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?
-s option is needed to print 2nd line from each file, otherwise only 2nd line of first file will be printed.
# Tell awk to print the third input record of the current file. awk 'FNR==3 {print}' my. txt.
NR and FNR are two built-in awk variables. NR tells us the total number of records that we've read so far, while FNR gives us the number of records we've read in the current input file.
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}'
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.
Use exit
to stop as soon as you've printed the desired record if there's no reason to process the whole file:
awk 'FNR == 2 {print; exit}'
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 }'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With