anti-conformiste anti-conformiste - 1 year ago 115
Linux Question

bash : merge text files ordered by numerical filenames

Is there any way to concatenate multiple text files in numerical order of the file names with one bash command ?

I tried this, but for some reason, the first three lines are not in order

sort -n *txt > all.txt

Answer Source

Adding this answer, only because the currently accepted answer suggests a bad practice. & In future, Hellmar may land in exact same problem I faced once. : Cannot delete an accepted answer.

Anyway, this should be the safe answer:

printf "%s\0" *txt | sort -zn | xargs -0 cat > all.txt

Here, entire pipeline has file names delimited by a NULL character. A NULL character is only character that cannot be part of file name.

Also, if all the filenames have same structure, (say file0001.txt, file0002.txt etc), then this code should work just as good:

cat file[0-9][0-9][0-9][0-9].txt > all.txt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download