gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:34:33 25 4
gpt4 key购买 nike

我有五个 csv 文件,我想使用 shell 函数将它们粘贴在一起。这基本上执行了几个文本文件中行的连接。在示例 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

这是输出:

col1    col2    col3               # <-- 1st file has 3 columns
col4 col5 # <-- 2nd file has 2 columns
col6 # <-- 3rd file has 1 columns
col7 # <-- 4th file has 1 columns
col8 col9 # <-- 5th file has 2 columns

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

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 |少:

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 标记。

最佳答案

将一些评论转移到(Community 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.

您确认这确实是问题的根源。

关于python - 如何对多个文件使用 unix/shell 粘贴命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33725958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com