2013-08-07 4 views
1

다음과 같이 두 개의 탭으로 구분 된 파일이 있습니다.다른 파일을 기반으로 파일에서 행을 제거하십시오.

첫 번째 파일 : -

raj krishna 2345  19041884 
dev sri  1573  13894083 
dev ravi  1232  54445434 

두 번째 파일 : - 나는 두 번째 파일의 첫 번째 3 필드와 일치하는 첫 번째 파일의 모든 라인을 제거 할

dev sri  1573  42334334 
kar ham  3214  45354354 

. 따라서, 제거한 후의 출력 첫 번째 파일은 다음과 같아야합니다.

raj krishna 2345  19041884 
dev ravi  1232  54445434 

누구나 내가 펄이나 셸 스크립팅에서 어떻게 이것을 달성 할 수 있는지 말할 수 있습니다.

감사

답변

1

이 그것을 만드는 :

$ awk 'NR == FNR{a[$3];next} !($3 in a)' file2 file1 
raj krishna 2345  19041884 
dev ravi  1232  54445434 

그것은 먼저 파일 2의 3 필드를 저장합니다. 그런 다음이 세 번째 필드가없는 행 또는 file1을 인쇄합니다.

two-file processing을 기반으로합니다.

+0

답장을 보내 주셔서 감사합니다. 위의 내용은 세 번째 필드 만 사용합니다. 1, 2, 3 번째 필드를 함께 사용하여 선을 제거하려면 위의 스크립트를 어떻게 바꿀 수 있습니까? – Dev

+0

@srikanth '$ 1, $ 2, $ 3'의 모든 '$ 3'을 변경할 수 있습니다. 예를 들어'{a [$ 1, $ 2, $ 3]; next}'. – fedorqui

1

Perl 용액. 나는 그것을 테스트로 포장하여 테스트 할 수 있습니다.

#!/usr/bin/perl 

use strict; 
use warnings; 

use autodie qw(open); 

use Test::More tests => 1; 

# I initialize the data within the test 
# the real code would skip this, and open the real files instead 

my $file1="raj krishna 2345 19041884 
dev sri 1573 13894083 
dev ravi 1232 54445434 
"; 

my $file2="dev sri 1573 42334334 
kar ham 3214 45354354 
"; 

my $expected="raj krishna 2345 19041884 
dev ravi 1232 54445434 
"; 

my $file_out; 

open(my $in1, '<', \$file1); # read from a string 
open(my $in2, '<', \$file2); 
open(my $out, '>', \$file_out); # write to a string 

# below is the real code  

# load the list of "records" to remove 
# for each line take the first 3 fields (anything except a tab followed by a tab, 3 times) 
my %to_remove= map { line_to_key($_) => 1 } <$in2>; 

while(my $line=<$in1>) 
    { print {$out} $line unless $to_remove{line_to_key($line)}; } 

close $out; 

# test whether we got what we wanted 
is($file_out, $expected, 'basic test'); 

# the "key": split on tab, then join the first 3 fields, again tab separated 
sub line_to_key 
    { my($line)= @_; 
    my @fields= split /\t/, $line; 
    my $key= join "\t", @fields[0..2]; 
    return $key; 
    } 
관련 문제