3

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
jww
  • 97,681
  • 90
  • 411
  • 885

3 Answers3

3

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
Community
  • 1
  • 1
anishsane
  • 20,270
  • 5
  • 40
  • 73
  • Thank you for awnsering. I tried it. But it doesn't order the files :( Maybe because of filenames : file1, file2, file3, file4, file5, file6, file7, file8, file9, file10, file 11, file12.... – anti-conformiste Feb 01 '16 at 10:50
  • I use Terminal on Mac and the commands below doesn't order the files – anti-conformiste Feb 01 '16 at 10:59
  • 1
    You have `file` prefixed to numbers. See if your `sort` supports `-V` option. If yes, use `-V` instead of `-n`. – anishsane Feb 01 '16 at 11:53
  • ls -1 | sort -n give me analyse_0.txt analyse_1.txt analyse_10.txt analyse_100.txt analyse_101.txt analyse_102.txt analyse_103.txt analyse_104.txt analyse_105.txt analyse_106.txt analyse_107.txt analyse_108.txt analyse_109.txt analyse_11.txt analyse_110.txt – anti-conformiste Feb 01 '16 at 12:01
  • Ok, I suffixed. That's was my mistake. Prefix it with automator got it work. How to prefix with bash command ? – anti-conformiste Feb 01 '16 at 12:07
  • If your sort supports `-V` option, you might not need to rename your files. If not and if you already have files created, you may rely on the perl based `rename` utility to rename the files – anishsane Feb 01 '16 at 12:23
1
ls *txt | sort -n | xargs cat > all.txt

This gets a list of all the filenames and sorts it, then uses xargs to construct a command line from cat and the sorted list.

Hellmar Becker
  • 2,824
  • 12
  • 18
1

update for anishsane's answer.

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

thecharlocation is the first key you want to sort. If your file name is file01.txt, thecharlocation is 5.

See also another similar answer from Nate in this question.

Community
  • 1
  • 1
Leung Yam
  • 11
  • 1