首页 文章

在perl脚本中编写awk命令

提问于
浏览
2

我有两种类型的制表符分隔输入文件,第一种是在第一列中垂直列出名称的矩阵,以及后续列中的数值 . 第二种类型的输入包含单个列,其中第一个文件类型的第一列中列出了相同名称的子集 .

EX:input1

Gary 1 2 3
Yolanda 3 4 5
Biff 5 6 7
Hubert 8 9 10

EX:input2

Gary
Biff

虽然input2有几种不同的变体,但只有一个输入1 . 我有一个带有嵌入式awk命令的perl脚本,该命令应该匹配input2和input1中的名称,并打印一个输出文件,其中包含input2中的名称和input1中的相应值 .

EX:outputfile

Gary 1 2 3
Biff 5 6 7

这是我的代码:

#!/usr/bin/perl

use strict;
use warnings;

my $dir1 = '../FeatureSelection/Chunks/ArffPreprocessing';
my $dir2 = '../DataFiles';

opendir(DIR, $dir1) or die $!;
while (my $file = readdir(DIR)) {

    # We only want files
    next unless (-f "$dir1/$file");

    # Use a regular expression to find files with .txt
    next unless ($file =~ m/\.txt/);

    my @partialName = (split /\./, $file);

    #The $matchingFile is the file which contains attributes listed vertically, along side their respective data

    my $matchingFile = "$dir2/input1\.txt ";

    system("awk -F\"\t\" 'FILENAME==\"$dir1/$file\"{a[\$1]=\$1} FILENAME==\"$matchingFile\"{if(a[\$1]){print \$0}}' $dir1/$file $matchingFile > $dir1/$partialName[0]'\_matched.out' ");

}

closedir(DIR);
exit 0;

这是在命令行上工作的行,但它拒绝在我的perl脚本中工作 .

awk -F"\t" 'FILENAME=="input2.txt"{a[$1]=$1} FILENAME=="../../../DataFiles/input1.txt"{if(a[$1]){print $0}}' input2.txt ../../../DataFiles/input1.txt > input2_matched.out

顺便说一句,input2文件的绝对数量使命令propt上面的awk行的硬编码真的很痛苦,这就是为什么我使用了一个perl脚本,它可以在目录中的每个input2文件上执行我想要的功能,并保留输出文件的命名约定 . 我写过类似的程序,所以我知道它的语法

system("awk ...blah blah... ");

可以而且确实有效 .

我已经坚持这个问题好几天了,所以任何帮助都会非常感激!

1 回答

  • 0

    虽然input2有几种不同的变体,但只有一个输入1 . 我有一个带有嵌入式awk命令的perl脚本,该命令应该匹配input2和input1中的名称,并打印一个输出文件,其中包含input2中的名称和input1中的相应值 .

    我建议 find a comparison function 来实现你的目标

    matcher(){
    awk 'NR==FNR{input1record[$1]=$0;next}
        $1 in input1record{print input1record[$1]}' /path/to/input1 "$@" >> /path/to/result
    }
    export -f matcher
    find /path/to/input2_files -type f -name "input2" \
         -exec bash -c 'matcher "$@"' _ {} +
    

    References

    • {} + with find构建命令行并执行subshell命令,在这种情况下我们的函数,一劳永逸 . 请参见[ find ]联机帮助页 .

    • 注意我已经使用 >> 将后续运行的输出附加到输出文件 . 如果不希望这样使用 > .

    • 应调整 -name 的模式以匹配所有 input2 文件名

相关问题