1

Related to my previous question....

I want to get a line where the first column has a certain string from 5000 files. But I want to show the lines in the output file by the order of input files. For example,

File_1

agd fkg fls  ofk
ggs kkg ikg  gkl
bsg ksf olg  lzj
many more lines,,,
kgf kkg ikg  lgk

File_2

gik zlg olg  pzk
ppl sjg gol  dzj
zjg iwj bmh  hgi
many more lines,,,
kgf wlg ugk  lkf

many more files...

Output_file

kgf kkg ikg lgk  -- This line from the File_1
kgf wlg ugk lkf  -- This is from the File_2
more lines...
kgf ald fig wdg  -- This last line is from the File_5000 

Just getting a line from multiple files can be as below.

grep -rEh `kgf` File_* > Output_file

But if I do this, output_file shows lines in the random order. The first line of the Output file can be from File_20 or others, and not the File_1. So I want the output_file to show the line from File_1 in the first line of output file, File_2 to be the 2nd line of output file, File_3 to be the 3rd of output file, etc.

Does anybody know this?

Thank you in advance!

1 Answer 1

3

The order of the expansion of File_* is not random. Shell globbing sorts the filenames lexically (using strcmp() (byte to byte comparison) or strcoll() (user's locale collation order) depending on the shell).

That means however that File_10 will come before File_2.

For a numeric order, you can use the zsh shell and do:

grep -h '^kgf' File_*(n) > Output_file

Where the n glob qualifier turns on the numericglobsort option (another zsh-specific feature) for the expansion of that glob only.

If on a GNU system (the -h option which you're using is already a GNU extension) and with any shell, you could do something similar with:

printf '%s\0' File_* | sort -zV | xargs -r0 grep -h '^kgf' > Output_file

Where sort -V is a version sort which behaves similarly to zsh's numeric glob sort.

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.