file1とfile2の列に一致するPerl印刷行

file1とfile2の列に一致するPerl印刷行

ここで印刷した内容は、一致しないファイルの内容です。私はその逆にしたいと思います。つまり、file1の行(file2で一致する行)を印刷したいと思います。

#!/usr/bin/perl

# create names lookup table from first file
my %names;
while (<>) {
    (my $col1)= split / /, $_;
    $names{$col1} = 1;
    last if eof;
}

# scan second file
while (<>) {
    print if /^(\S+).*/ && not $names{$1};
}

この質問を参考にしてください2つのファイルを最初の列と比較し、シェルスクリプトの2番目のファイルから重複行を削除します。。重複したアイテムを削除したくなく、列の内容に一致するアイテムを印刷し、残りのアイテムを保持したいと思います。

ベストアンサー1

@chorobaがコメントで指摘したように、削除するだけですnot。以下は少し複雑なバージョンです。

#!/usr/bin/perl

## Add command line switches
use Getopt::Std;

## This hash will hold the options
my %opts;

## Read the options
getopts('d',\%opts);

# create names lookup table from first file
my %names;
while (<>) {
    ## Remove trailing newlines. This is needed
    ## for cases where you only have a single word
    ## per line.
    chomp;

    my $col1=split(/\s+/, $_);
    $names{$col1} = 1;
    last if eof;
}
# scan second file
while (<>) {
    ## Skip any lines we don't care about
    next unless /^(\S+)/;

    ## Do we want the duplicates or not?
    defined $opts{d} ? 
        do{print if $names{$1}} :
        do{print unless $names{$1}};
}

-dフラグ()を使用して上記のスクリプトを実行すると、両方のファイルの名前が印刷されfoo.pl -d file、フラグがない場合は最初のファイルの名前のみが印刷されます。

を使用すると、ほぼ同じことができますgrep。被害者を見つけるには:

grep -wFf file1 file2

だまされない人のために:

grep -vwFf file1 file2

ただし、上記は次の内容と一致します。file1 どこかにでは、file2行の先頭だけでなく

おすすめ記事