Delete a pattern present in file 2 from file 1 if found in file 1.

I have two files

File1
====
1|2000-00-00|2010-02-02||
2| 00:00:00|2012-02-24||
3|2000-00-00|2011-02-02||

File2
====
2000-00-00
 00:00:00

I want the delete the patterns which are found in file 2 from file 1,

Expected output:

File1
====
1||2010-02-02||
2||2012-02-24||
3||2011-02-02||

I did something like

while read line
  do
     sed 's/'$line'//g' File1 > File1_tmp
     mv File1_tmp File1
  done < File2

Not sure if this is good approach. Can someone help me with some better solution?

  1. This would only remove that part of string from file1 which matches with file2. It won't remove the whole line from file1.
  2. You may do this:
while read line
do
    grep $line file1 >> file1_tmp
done < file2
mv file1_tmp file1
  1. Or you may also do this:
grep -fv file2 file1

I just wanted to remove the data in file1 which matches the pattern in file2. Not the whole line.:o

Hi machomaddy,

One way using perl:

$ cat file1
1|2000-00-00|2010-02-02||
2| 00:00:00|2012-02-24||
3|2000-00-00|2011-02-02||
$ cat file2
2000-00-00
 00:00:00
$ cat script.pl
use warnings;
use strict;

die qq[Usage: perl $0 <file-1> <file-2>\n] unless @ARGV == 2;

open my $fh1, qq[<], shift @ARGV or die qq[Cannot open input file\n];
open my $fh2, qq[<], shift @ARGV or die qq[Cannot open input file\n];

my (@patterns, $pattern, $re);

while ( <$fh2> ) {
        next if m/\A\s*\Z/;
        s/\A\s+/\\s*/;
        s/\s+\Z/\\s*/;
        push @patterns, $_;
}

$pattern = join qq[|], @patterns;
$re = qr/($pattern)/;

while ( <$fh1> ) {
        do { print, next } if m/\A\s*\Z/;
        chomp;
        s/$re//go;
        printf qq[%s\n], $_;
}
$ perl script.pl file1 file2
1||2010-02-02||
2||2012-02-24||
3||2011-02-02||

Regards,
Birei

See if this works:

awk -F\| 'NF==1{A[$1];next}$2 in A{$2=x}1' OFS=\| file2 file1

try this

awk -F, 'NR==FNR{a[$0]=$0;next} {for(i in a) gsub(i,""); print} ' file_with_pattern file