Remove all lines in file A which contain the strings in file B

202 Views Asked by At

I have 2 text file and want remover lines in file A which contain the strings in file B

file A:

joe     ball     1335
john    dyer     1365
dylan   fisher   1795
ian     gill     1913
eric    kelly    1101

file B:

1795
1913

And I want Bash code get result like this:

joe     ball     1335
john    dyer     1365
eric    kelly    1101

I try this codes but the answer did not work out

$ grep -vwF -f A B
$ awk -F'[ ,]' 'FNR==NR{a[$1];next} !($4 in a)'
3

There are 3 best solutions below

2
On BEST ANSWER
awk  'NR==FNR{a[$1];next} !($3 in a)' fileB fileA

It uses space as field separator, and $1 is the first column element of a line, $3 is the 3rd column element of the line. use array a store fileB elements a[$1]. checks the 3rd column element of fileA whether in array a, if not print the whole line Output:

joe     ball     1335
john    dyer     1365
eric    kelly    1101
0
On

Using grep:

$ grep -v -f B A
joe     ball     1335
john    dyer     1365
eric    kelly    1101

That is at the simplest but will create collisions under circumstances. If you mangle B a bit with for example sed first (add space to beginning and $ to the end of search strings):

$ sed 's/$/$/;s/^/ /' B
 1795$
 1913$

and use it in process substitution:

$ grep -v -f <(sed 's/$/$/;s/^/ /' B) A
joe     ball     1335
john    dyer     1365
eric    kelly    1101
4
On

cat file_B | while read values; do grep $values file_A >> newfile; done