连接文件并在文件之间插入新行
我有多个文件想要与 cat
连接。 假设
File1.txt
foo
File2.txt
bar
File3.txt
qux
我想连接,使最终文件看起来像:
foo
bar
qux
而不是通常的 cat File*.txt > Finalfile.txt
foo
bar
qux
正确的方法是什么?
I have multiple files which I want to concat with cat
.
Let's say
File1.txt
foo
File2.txt
bar
File3.txt
qux
I want to concat so that the final file looks like:
foo
bar
qux
Instead of this with usual cat File*.txt > finalfile.txt
foo
bar
qux
What's the right way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以执行以下操作:
在运行上述命令之前,确保文件
finalfile.txt
不存在。如果您被允许使用
awk
您可以执行以下操作:You can do:
Make sure the file
finalfile.txt
does not exist before you run the above command.If you are allowed to use
awk
you can do:如果您的文件数量足够少,可以列出每个文件,那么您可以使用进程替换 在 Bash 中,在每对文件之间插入换行符:
If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:
如果是我这样做,我会使用 sed:
在这个 sed 模式中 $ 有两个含义,首先它仅匹配最后一个行号(作为要应用模式的行范围),其次它匹配行尾在替换模式中。
如果您的 sed 版本没有
-s
(单独处理输入文件),您可以将其作为循环完成:If it were me doing it I'd use sed:
In this sed pattern $ has two meanings, firstly it matches the last line number only (as a range of lines to apply a pattern on) and secondly it matches the end of the line in the substitution pattern.
If your version of sed doesn't have
-s
(process input files separately) you can do it all as a loop though:这在 Bash 中有效:
与
>>
(附加)的答案相比,该命令的输出可以通过管道传输到其他程序中。示例:
for f in File*.txt;做猫$f;回声;完成> Finalfile.txt
(对于...完成)> Finalfile.txt
(括号是可选的)for ... 完成 | less
(管道到 less)for ... 完成 | head -n -1
(这会去除尾随的空白行)This works in Bash:
In contrast to answers with
>>
(append), the output of this command can be piped into other programs.Examples:
for f in File*.txt; do cat $f; echo; done > finalfile.txt
(for ... done) > finalfile.txt
(parens are optional)for ... done | less
(piping into less)for ... done | head -n -1
(this strips off the trailing blank line)如果您愿意,可以使用 xargs 来完成此操作,但主要思想仍然相同:
You may do it using
xargs
if you like, but the main idea is still the same:这就是我在 OsX 10.10.3 上所做的,
因为没有参数的简单“echo”命令最终没有插入新行。
That's how I just did it on OsX 10.10.3
since the simple 'echo' command with no params ended up in no new lines inserted.
您可以使用
grep
和-h
来不回显文件名将给出:
You could use
grep
, with-h
to not echo the filenamesWill give:
在 python 中,这会在文件之间连接空行(
,
禁止添加额外的尾随空行):这是丑陋的 python 单行代码,可以从 shell 调用并将输出打印到文件:
In python, this concatenates with blank lines between files (the
,
suppresses adding an extra trailing blank line):Here is the ugly python one-liner that can be called from the shell and prints the output to a file:
POSIX 兼容的解决方案是使用 cat,但在每个文件中插入一个仅包含空行的文件。
更奇特的版本可能是一些线条。
A POSIX compatible solution is to use cat, but interlude each file with a file containing only a blank line.
A more fancy version might be something line.