分页: 1 / 2

如何合并文件阿?

发表于 : 2009-06-19 23:11
nangergong
比如一个文件是
1
2
3
另一个文件是
a
b
c
現在要合并为的文件是
1 a
2 b
3 c

Re: 如何合并文件阿?

发表于 : 2009-06-19 23:22
ptpt52
自己写 个 程序 吧

Re: 如何合并文件阿?

发表于 : 2009-06-19 23:25
peachcolor
用python写个脚本倒是很简单,用sh的话不知道了。

Re: 如何合并文件阿?

发表于 : 2009-06-19 23:30
nangergong
那就用python也行阿
怎么弄阿

Re: 如何合并文件阿?

发表于 : 2009-06-19 23:50
oneleaf

代码: 全选

a=open("a.txt")
b=open("b.txt")
c=open("c.txt","w")
for a1 in a.readlines():
    for b1 in b.readlines():
         c.write(a1.strip()+' '+b1)
c.close()

Re: 如何合并文件阿?

发表于 : 2009-06-19 23:59
ptpt52

代码: 全选

a=open("a.txt")
b=open("b.txt")
c=open("c.txt","w")
for a1 in a.readlines():
         c.write(a1+' '+b.readlines())
c.close()
应该这样吧 :em09

Re: 如何合并文件阿?

发表于 : 2009-06-20 0:04
nangergong
非常感谢

Re: 如何合并文件阿?

发表于 : 2009-06-20 0:10
oneleaf

代码: 全选

a=open("a.txt")
b=open("b.txt")
c=open("c.txt","w")
for a1 in a.readlines():
     c.write(a1.strip()+' '+b.readline())
c.close()
太困,迷糊了。

Re: 如何合并文件阿?

发表于 : 2009-06-20 0:59
cheeselee
来段Perl,虽然不太严谨:

代码: 全选

#!/usr/bin/perl
open A,"<a.txt";
open B,"<b.txt";
open C,">c.txt";
while (chomp($a=<A>) and $b=<B>){
    print C "$a $b";
}

Re: 如何合并文件阿?

发表于 : 2009-06-20 13:21
xhy

代码: 全选

a = open("1")
b = open("2")
c = open("3", "w")
for l in zip(a,b):
    c.write("%s %s" %(l[0][:-1], l[1]) )

Re: 如何合并文件阿?

发表于 : 2009-06-20 13:24
xhy

代码: 全选

a = open("1")
b = open("2")
c = open("3", "w")
map(lambda l:c.write("%s %s" %(l[0][:-1], l[1])), zip(a,b) )

Re: 如何合并文件阿?

发表于 : 2009-06-21 16:55
sinic
nangergong 写了:比如一个文件是
1
2
3
另一个文件是
a
b
c
現在要合并为的文件是
1 a
2 b
3 c

paste file1 file2 >file3
详细的man paste

Re: 如何合并文件阿?

发表于 : 2009-06-21 17:26
chpn
佩服ls

Re: 如何合并文件阿?

发表于 : 2009-06-25 15:12
tusooa

代码: 全选

#!/usr/bin/env python
import sys
fa = file(sys.argv[1],'r')
fb = file(sys.argv[2],'r')
fc = file(sys.argv[3],'w')
c = ""
while True:
    la = fa.readline()
    lb = fb.readline()
    c = c + la + " " + lb
    if len(la) == 0 or len(lb) == 0:
        break

fa.close()
fb.close()
fc.write(c)
fc.close()

Re: 如何合并文件阿?

发表于 : 2009-07-02 17:58
kwarph
凑个热闹,C++的(比较笨重)

代码: 全选

#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
    if (argc < 4)
        cout << "Usage: " << argv[0] << " inputfile1 inputfile2 outputfile"
                << endl;

    ifstream fin1(argv[1]);
    ifstream fin2(argv[2]);

    if (fin1.fail()) {
        cerr << "open file " << argv[1] << " failed." << endl;
        return 1;
    }

    if (fin2.fail()) {
        cerr << "open file " << argv[2] << " failed." << endl;
        return 1;
    }

    ofstream fout(argv[3]);

    string line1, line2;
    while (getline(fin1, line1)) {
        getline(fin2, line2);
        fout << line1 << ' ' << line2 << endl;
    }

    fout.close();
    fin2.close();
    fin1.close();

    return 0;
}