Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select row and element in awk

Tags:

awk

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?

like image 730
Tim Avatar asked Oct 01 '09 21:10

Tim


People also ask

How do you get the second line in awk?

-s option is needed to print 2nd line from each file, otherwise only 2nd line of first file will be printed.

How do I print a third line in awk?

# Tell awk to print the third input record of the current file. awk 'FNR==3 {print}' my. txt.

What is NR and FNR in awk?

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.


2 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}' 

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}' 
like image 197
Dennis Williamson Avatar answered Oct 07 '22 01:10

Dennis Williamson


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 }' 
like image 20
Hai Vu Avatar answered Oct 06 '22 23:10

Hai Vu