本文介绍了在Bash中按数字文件名排序的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用一个bash命令按文件名的数字顺序连接多个文本文件?

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

推荐答案

添加此答案,只是因为当前接受的答案建议不良做法. &将来,Hellmar可能会遇到完全相同的问题我遇到过一次.:

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

在这里,整个管道的文件名都以NULL字符分隔. NULL字符仅是不能作为文件名一部分的字符.

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

此外,如果所有文件名都具有相同的结构(例如file0001.txt,file0002.txt等),则此代码应同样有效:

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

这篇关于在Bash中按数字文件名排序的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:21