Deleting record in a file by looking up another file

I have two files which are pipe delimited "|". Also, each record in these files will end with a "|"

File 1

EMPID|NAME|DEPT
1|AAA|PPP
2|BBB|QQQ
3|CCC|RRR
4|DDD|SSS
5|EEE|TTT

File 2 (EMPID of those employees who have left the organisation)

EMPID|
2|
5|

I have to delete the records of emplyees in file 1 if their EMPID is found in file 2

Expected output

File 1

EMPID|NAME|DEPT
1|AAA|PPP
3|CCC|RRR
4|DDD|SSS

It would be greatful if someone helps me with this

$fgrep -v -f file2 file1
1|AAA|PPP
3|CCC|RRR
4|DDD|SSS

Thanks a lot :slight_smile: it worked...can you explain me how this works :smiley:

we are using fgrep here

 
-f file1 file2 ---> search file1 pattern in the file2
-v    Prints all lines except those that  contain  the  pat-
           tern.

Ok..But if the File 2 contains more than one field, then this will not work correct? Can you please tell me how to handle this.

Let Say,

File 2

EMPID|NAME|DEPT|RESIGNREQNO
2|BBB|QQQ|5
5|EEE|TTT|2

In this case, I just want to check the EMPID column alone of each record in file 2 and then delete the corresponding record in file1

:o

---------- Post updated at 03:18 PM ---------- Previous update was at 02:59 PM ----------

Some one please help on this. :slight_smile:

if file2 contains more than one field also, it will work ( as long as the file2 line is present in the file1)

$ cat file1
EMPID|NAME|DEPT
1|AAA|PPP
2|BBB|QQQ
3|CCC|RRR
4|DDD|SSS
5|EEE|TTT

$ cat file2
EMPID|NAME|DEPT|RESIGNREQNO
2|BBB|QQQ|5
5|EEE|TTT|2

$ awk -F\| '$1~/^[0-9]/{a=$1"|"a} END{printf("egrep -v \"%s\" file1",substr(a,1,length(a)-1))}' file2 | sh
EMPID|NAME|DEPT
1|AAA|PPP
3|CCC|RRR
4|DDD|SSS
1 Like

Thanks... it works!! you are awesome :cool:

Alternatively:

awk -F\| 'NR==FNR{A[$1]=1;next} NR==1 || !A[$1]' file2 file1

-or-
in bash:

grep -vf <(sed '1d;s/^/^/' file2) file1
1 Like

The awk code works fine...but the sed is not working.
Could you please explain the awk code?

Also, the awk code returns a blank line at the end!!