如何合并2个文件

时间:2019-08-04 10:32:44

标签: python bash perl

不幸的是,我没有发现有用的东西,也没有找到解决方法的线索。

我想将两个文件之间的所有组合保存在一个文件中

first.txt

Black
Blue
Brown
Orange
Red

two.txt

one
two
three
four

我要在输出文件中添加此内容

 Black:one
 Black:two
 Black:three
 Black:four
 Blue:one
 Blue:two
 Blue:three
 Blue:four
 Brown:one
 Brown:two
 Brown:three
 Brown:four
 Orange:one
 Orange:two
 Orange:three
 Orange
 Red:one
 Red:two
 Red:three
 Red:four

不幸的是,我没有发现有用的东西,也没有找到解决方法的线索。

希望您能为我提供帮助,它应该在debian下运行

致谢

4 个答案:

答案 0 :(得分:2)

有两个while循环:

while read -r first; do while read -r second; do echo "$first:$second"; done <second.txt; done <first.txt

或缩进:

while read -r first; do 
  while read -r second; do
    echo "$first:$second"
  done <second.txt
done <first.txt

输出:

Black:one
Black:two
Black:three
Black:four
Blue:one
Blue:two
Blue:three
Blue:four
Brown:one
Brown:two
Brown:three
Brown:four
Orange:one
Orange:two
Orange:three
Orange:four
Red:one
Red:two
Red:three
Red:four

请参阅:man bash

答案 1 :(得分:2)

最简单的是 GNU Parallel (这是Perl脚本):

parallel echo {1}:{2} :::: first.txt :::: two.txt

如果您希望输出保持井井有条,请使用:

parallel -k ...

如果要在result.txt中输出:

parallel ... > result.txt

答案 2 :(得分:0)

f=open("first.txt")
s=open("second.txt")

for i in f:
    for j in s:
        print(i+":"+j)
    s.seek(0)

在python中。

立即尝试:

f=open("first.txt")
s=open("second.txt")

for i in f:
    for j in s:
        print(i.replace("\n","")+":"+j.replace("\n",""))
    s.seek(0)

以文本格式保存:

f=open("first.txt")
s=open("second.txt")
k=open("third.txt",'w')

for i in f:
    for j in s:
        k.write(i.replace("\n","")+":"+j.replace("\n",""))
        k.write("\n")
    s.seek(0)

k.close()

答案 3 :(得分:0)

for first in $(cat first.txt)
do 
    for two in $(cat two.txt)
    do 
        echo "$first:$two"
    done
done

输出:

Black:one
Black:two
Black:three
Black:four
Blue:one
Blue:two
Blue:three
Blue:four
Brown:one
Brown:two
Brown:three
Brown:four
Orange:one
Orange:two
Orange:three
Orange:four
Red:one
Red:two
Red:three
Red:four