Select row and element in awk

前端 未结 4 927
温柔的废话
温柔的废话 2021-01-29 18:17

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?

4条回答
  •  萌比男神i
    2021-01-29 19:04

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

提交回复
热议问题