Bash: Filter rows by line number

awksedtext processing

If I have a delimited file with many lines and columns (data.txt):

346 dfd asw  34
565 sd  wdew 34
667 ffg wew  23
473 sa  as   21
533 jhf qwe  54

and another file with line numbers that I want to extract (positions.txt)

3
5
8

How do I use the positions.txt file to extract those positions from data.txt? This is the result I would expect for this example:

667 ffg wew  23
533 jhf qwe  54

Best Answer

Simply with awk:

awk 'NR==FNR{ pos[$1]; next }FNR in pos' positions.txt data.txt
  • NR==FNR{ ... } - processing the 1st input file (i.e. positions.txt):
    • pos[$1] - accumulating positions(record numbers) set as pos array keys
    • next - jump to next record
  • FNR in pos - while processing the 2nd input file data.txt(FNR indicates how many records have been read from the current input file). Print record only if current record number FNR is in array of positions pos (search on keys)

Sample output:

667 ffg wew  23
533 jhf qwe  54
...
Related Question