连接文件并在文件之间插入新行

问题描述 投票:0回答:10

我有多个文件想要与

cat
连接。 就说吧

File1.txt 
foo

File2.txt
bar

File3.txt
qux

我想连接,使最终文件看起来像:

foo

bar

qux

而不是平常的

cat File*.txt > finalfile.txt

foo
bar 
qux

正确的做法是什么?

linux unix cat
10个回答
192
投票

你可以这样做:

for f in *.txt; do (cat "${f}"; echo) >> finalfile.txt; done

在运行上述命令之前,请确保文件

finalfile.txt
不存在。

如果您被允许使用

awk
,您可以这样做:

awk 'FNR==1{print ""}1' *.txt > finalfile.txt

82
投票

如果您的文件数量足够少,可以列出每个文件,那么您可以在 Bash 中使用进程替换,在每对文件之间插入换行符:

cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt

42
投票

如果是我这样做,我会使用 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

19
投票

这在 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
    (这会去除尾随的空白行)

14
投票

如果你愿意,你可以使用

xargs
来完成,但主要思想仍然是一样的:

find *.txt | xargs -I{} sh -c "cat {}; echo ''" > finalfile.txt

10
投票

我刚刚在 OsX 10.10.3 上就是这样做的

for f in *.txt; do (cat $f; echo '') >> fullData.txt; done

因为没有参数的简单“echo”命令最终没有插入新行。


6
投票

您可以使用

grep
-h
来不回显文件名

grep -h "" File*.txt

将给予:

foo
bar 
qux

3
投票

在Python中,这与文件之间的空行连接(

,
抑制添加额外的尾随空行):

print '\n'.join(open(f).read() for f in filenames),

这是丑陋的 python 单行代码,可以从 shell 调用并将输出打印到文件中:

python -c "from sys import argv; print '\n'.join(open(f).read() for f in argv[1:])," File*.txt > finalfile.txt

0
投票

POSIX 兼容的解决方案是使用 cat,但在每个文件之间插入一个仅包含空行的文件。

nl=`mktemp`
printf '\n' > $nl
cat file1 $nl file2 $nl file3
rm $nl

更奇特的版本可能会更符合要求。

nl=`mktemp`
printf '\n' > $nl
find file1 file2 file3 -print0 |
  xargs -0 printf "%s\0$nl\0" |
  tr '\0' '\n' |
  sed -n '$!p;$q' |
  tr '\n' '\0' |
  xargs -0 cat
rm $nl

0
投票

受到@hustnzj的启发,

awk '{ORS="\n\n"}  1' *.txt |  head -c-1

如果您希望每个文件的内容之间有额外的空行,而不是仅从换行符开始

© www.soinside.com 2019 - 2024. All rights reserved.