【发布时间】:2012-01-01 06:18:02
【问题描述】:
我有多个文件想与cat 连接。
比方说
File1.txt
foo
File2.txt
bar
File3.txt
qux
我想连接,使最终文件看起来像:
foo
bar
qux
而不是通常的cat File*.txt > finalfile.txt
foo
bar
qux
正确的做法是什么?
【问题讨论】:
我有多个文件想与cat 连接。
比方说
File1.txt
foo
File2.txt
bar
File3.txt
qux
我想连接,使最终文件看起来像:
foo
bar
qux
而不是通常的cat File*.txt > finalfile.txt
foo
bar
qux
正确的做法是什么?
【问题讨论】:
你可以这样做:
for f in *.txt; do (cat "${f}"; echo) >> finalfile.txt; done
在运行上述命令之前,请确保文件 finalfile.txt 不存在。
如果你被允许使用awk,你可以这样做:
awk 'FNR==1{print ""}1' *.txt > finalfile.txt
【讨论】:
AWK '{print $0}' *.txt
awk 'FNR==1 && NR > 1 ...' 轻松防范这种情况。
>finalfile.txt 放在done 之后,您可以覆盖而不是追加,这将消除在循环之前确保文件丢失或为空的要求。
如果您有足够少的文件可以列出每个文件,那么您可以在 Bash 中使用 process substitution,在每对文件之间插入一个换行符:
cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt
【讨论】:
… | xargs -I{} kubectl -n alex exec {} -- cat blah.log <(echo) >> blahblah.logs cat: /dev/fd/63: 没有这样的文件或目录,命令以退出代码 1 终止
<(echo) 在本地运行。也许-- bash -c "cat blah.log <(echo)"?
sh -c "echo -e '\n\n' | cat - /../logs/a.log"
如果是我这样做,我会使用 sed:
sed -e '$s/$/\n/' -s *.txt > finalfile.txt
在这个 sed 模式中,$ 有两个含义,首先它只匹配最后一个行号(作为应用模式的行范围),其次它匹配替换模式中的行尾。
如果您的 sed 版本没有 -s(单独处理输入文件),您可以将其全部作为循环来完成:
for f in *.txt ; do sed -e '$s/$/\n/' $f ; done > finalfile.txt
【讨论】:
sed -s '$G' *.txt > finalfile.txt
find 代替了*.txt,这意味着文件被附加到自身!
这适用于 Bash:
for f in *.txt; do cat $f; echo; done
与>>(附加)的答案相比,此命令的输出可以通过管道传输到其他程序中。
例子:
for f in File*.txt; do cat $f; echo; done > finalfile.txt(for ... done) > finalfile.txt(括号是可选的)for ... done | less(进入 less)for ... done | head -n -1(这会去掉尾随的空行)【讨论】:
如果你愿意,你可以使用xargs,但主要思想还是一样的:
find *.txt | xargs -I{} sh -c "cat {}; echo ''" > finalfile.txt
【讨论】:
xargs 比 bash 中的循环更容易使用。
这就是我在 OsX 10.10.3 上的做法
for f in *.txt; do (cat $f; echo '') >> fullData.txt; done
因为没有参数的简单“echo”命令最终没有插入新行。
【讨论】:
在 python 中,这与文件之间的空行连接(, 禁止添加额外的尾随空行):
print '\n'.join(open(f).read() for f in filenames),
这是可以从 shell 调用并将输出打印到文件的丑陋的 python one-liner:
python -c "from sys import argv; print '\n'.join(open(f).read() for f in argv[1:])," File*.txt > finalfile.txt
【讨论】: