erge text files ordered by numerical filenames in Bash

耗尽温柔 提交于 2019-12-04 01:43:25

问题


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

回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/35126745/erge-text-files-ordered-by-numerical-filenames-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!