将目录中的所有*.txt文件合并到一个大文本文件中的最快捷,最实用的方法是什么?
目前我正在使用带有cygwin的windows,所以我可以访问BASH.
Windows shell命令也不错,但我怀疑有一个.
Rob*_*ner 482
这会将输出附加到all.txt
cat *.txt >> all.txt
Run Code Online (Sandbox Code Playgroud)
这会覆盖all.txt
cat *.txt > all.txt
Run Code Online (Sandbox Code Playgroud)
Chi*_*chi 133
请记住,对于目前为止给出的所有解决方案,shell决定了文件连接的顺序.对于Bash,IIRC,这是按字母顺序排列的.如果顺序很重要,您应该正确命名文件(01file.txt,02file.txt等等),或者按照您想要连接的顺序指定每个文件.
$ cat file1 file2 file3 file4 file5 file6 > out.txt
Run Code Online (Sandbox Code Playgroud)
Gre*_*ill 33
Windows shell命令type可以执行此操作:
type *.txt >outputfile
Run Code Online (Sandbox Code Playgroud)
Type type命令还将文件名写入stderr,这些名称不会被>重定向操作符捕获(但会显示在控制台上).
Car*_*rum 25
您可以使用Windows shell copy连接文件.
C:\> copy *.txt outputfile
Run Code Online (Sandbox Code Playgroud)
从帮助:
要附加文件,请为目标指定单个文件,但为源指定多个文件(使用通配符或file1 + file2 + file3格式).
使用shell最实用的方法是cat命令。其他方式包括
awk '1' *.txt > all.txt
perl -ne 'print;' *.txt > all.txt
Run Code Online (Sandbox Code Playgroud)
这种方法怎么样?
find . -type f -name '*.txt' -exec cat {} + >> output.txt
Run Code Online (Sandbox Code Playgroud)
请注意,因为这些方法都无法处理大量文件。我个人使用以下行:
for i in $(ls | grep ".txt");do cat $i >> output.txt;done
Run Code Online (Sandbox Code Playgroud)
编辑:正如某人在评论中所说,您可以替换$(ls | grep ".txt")为$(ls *.txt)
编辑:感谢@gnourf_gnourf的专业知识,使用glob是遍历目录中文件的正确方法。因此,$(ls | grep ".txt")必须将亵渎性的表达式替换为*.txt(请参阅此处的文章)。
好的解决方案
for i in *.txt;do cat $i >> output.txt;done
Run Code Online (Sandbox Code Playgroud)