如何对多个文件使用unix/shell粘贴命令

2024-10-01 07:15:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有五个csv文件,我想使用shell函数将它们paste一起使用。这基本上执行多个文本文件中的行的连接。我想要的在例8 in this tutorial

我是通过subprocess.call()从Python中执行此操作的,但是直接在终端中执行会产生同样令人困惑的结果。在

我的文件都是制表符分隔的(这是粘贴函数的默认分隔符)

当我在2,3。。。n个文件,似乎第二到第n个文件的头被添加为第二行,只有第一个文件的头在第一行。在

我的命令是:

paste outfile.txt tmp_1.txt tmp_2.txt tmp_3.txt tmp_4 > final.txt

输出如下:

^{pr2}$

然而,在这之后,行以不同的方式继续(一直到文件末尾):

col1    col2    col3
col4    col5    col6    col6    col7    col8    col9
col1    col2    col3
col4    col5    col6    col6    col7    col8    col9

[这两个代码块彼此相连]

我找不到更多可以在this documentation中指定的选项,显式地输入-d'\t'不会更改任何内容。我也尝试过更少或更多的文件,改变文件的顺序(以防我的第一个文件中有一些进位返回等),但结果总是一样的。在

更新1

以下是@shellter在注释中推荐的命令的输出片段:cat -vet file1.txt file2.txt ... file5.txt | less

Col1^ICol2^ICol3^M$
Some text was here^I2^I-3^M$
Some text was here^I2^I-1^M$
Some text was here^I2^I-2^M$
Some text was here^I2^I-1^M$

您可以看到制表符的^I标记,而^M$表示行尾/回车符/换行符。在

更新2

将shell函数dos2unix应用于我的文件:

dos2unix file1.txt file2.txt ... file5.txt

我最初使用的原始粘贴函数按预期工作。从最终文件的输出中,我们可以看到哪些标记只保留了有用的类型。以下是期望的结果:

col1    col2    col3    col4    col5    col6    col6    col7    col8    col9
col1    col2    col3    col4    col5    col6    col6    col7    col8    col9
col1    col2    col3    col4    col5    col6    col6    col7    col8    col9

这里是用于检查的函数的输出:cat -vet file1.txt ...

Col1^ICol2^ICol3^ICol4^ICol5^ICol6^Col7^ICol8^ICol9$
Col1^ICol2^ICol3^ICol4^ICol5^ICol6^Col7^ICol8^ICol9$
Col1^ICol2^ICol3^ICol4^ICol5^ICol6^Col7^ICol8^ICol9$

找不到^M标记。在


Tags: 文件函数txttmpcol2col3col1col4
1条回答
网友
1楼 · 发布于 2024-10-01 07:15:20

将一些评论转移到(社区Wiki)答案中。

Jonathan Leffler评论:

Have you got any DOS line endings confusing things? That is, do the files have CRLF line endings?

并且shellter评论道:

Use cat -vet file ... file | less and look for ^M at the end of each line.

你证实这确实是麻烦的根源。在

相关问题 更多 >