unix - commandline output lines that are specified in another file -
iam searching command line takes text file , file line numbers (one on each line) (alternatively stdin) , outputs lines first file.
the text file may several hundreds of mb large , line list may contains several thousands of entries (but sorted ascending)
in short:
- one file contains data
- another file contains indexes
- a command should extract indexed lines
first file:
many lines of course different , contain important data ... more lines ... more lines
second file
1 5 7
expected output
many lines more lines more lines
the second (line number) file not have exist. data may come stdin (in deed optimum). format of data may vary shown if make task easier.
this can approach:
$ awk 'fnr==nr {a[$1]; next} fnr in a' file_with_line_numbers file_with_data many lines more lines more lines
it reads file_with_line_numbers
, stores lines in array a[]
. reads other file , keeps checking if line number in array, in case line printed.
the trick used following:
awk 'fnr==nr {something; next} {other things}' file1 file2
that performs actions related file1
in {something}
block , actions related file2
in {other things}
block.
what if line numbers given through stdin?
for can use awk '...' - file
, stdin called -
. called naming standard input. can do:
your_commands | awk 'fnr==nr {a[$1]; next} fnr in a' - file_with_data
test
$ echo "1 5 7" | awk 'fnr==nr {a[$1]; next} fnr in a' - file_with_data many lines more lines more lines
Comments
Post a Comment