Skip to main content
1 of 4
Kusalananda
  • 355.9k
  • 42
  • 735
  • 1.1k

Using awk:

$ awk -v num="$num" 'NR == num { print $NF }' data.in

Testing it:

$ num=3
$ awk -v num="$num" 'NR == num { print $NF }' data.in
two

The awk script reads the input file record by record (a record is by default a line). Once it hits the record corresponding to the num variable, it prints the last field of that record (a field is by default a whitespace-separated column).

The num variable inside the awk script is an awk variable that we initialize to the value of the shell variable num with -v num="$num" on the command line.

NR is the current record number, and NF is the number of fields in this record. $NF is the data of the last field.

If your file is strictly comma-separated, add -F ',' to the command line:

$ awk -v num="$num" -F ',' 'NR == num { print $NF }' data.in
Kusalananda
  • 355.9k
  • 42
  • 735
  • 1.1k