从2个文本文件中输入perl以生成一个文本文件

时间:2010-08-10 14:06:19

标签: perl awk

我有一个文本文件(fileA),大约200行,每行格式为

afield1 afield2 afield3 afield4 afield5

和另一个文本文件(fileB),大约300行,相同的格式

bfield1 bfield2 bfield3 bfield4 bfield5

我想创建另一个文本文件,如果是afield1& bfield1匹配,它写一行如:

"some text" bfield4 "some text" afield3 "some text" afield1

我认为如果我知道如何,这在perl甚至是awk中都很容易做到。一个简单的shell脚本证明非常困难。

非常感谢收到的任何帮助。

由于

4 个答案:

答案 0 :(得分:1)

对于某些模块来说,这可能会更容易,但由于您似乎需要快速和肮脏的东西,这就是我能想到的。 (这假设您的文件以逗号分隔。如果您正在使用其他内容,请更改拆分调用中的分隔符。

open(my $fh1, "fileA.txt") or die $!;
open(my $fh2, "fileB.txt") or die $!;
open( my $out, ">outfile.txt") or die $!;
while( my $line = <$fh2> ) {
     chomp($line);
     my @columns_2 = split(/,/, $line);
     my $a_line = <$fh1>;
     my @columns_1 = split(/,/, $a_line);

     if( $columns_2[0] eq $columns_1[0] ) {
          print $out "text $columns_2[3] more text $columns_1[2] more text $columns_1[0]\n";
     }
}
close($fh1);
close($fh2);
close($out);

答案 1 :(得分:1)

awk 'FNR==NR{a[$1];next}($1 in a) {print "sometext "$4" some text blah"} ' file1 file2

下一次提供一个更具体的数据文件示例和预期输出。

答案 2 :(得分:1)

在Bash中:

join <(sort fileA) <(sort fileB) | awk '{print $8, "some text", $3, "some text", $1}'

如果您没有使用Bash,则可能需要对文件进行预排序。

sort fileA > temp1
sort fileA > temp2
join temp1 temp2 | awk '{print $8, "some text", $3, "some text", $1}'

答案 3 :(得分:0)

以ghostdog74的回答为基础

awk '
    # read file1 first
    FNR == NR {
        # store afield3 for later
        a[$1] = $3 
        next
    }
    ($1 in a) {
        # bfield1 == some afield1
        print "some text " $4 " some text " a[$1] " some text " $1
    } 
' file1 file2