0

I have two files, file1.txt contains strings separated by commas:

1.1.1.1,string1,comment1
7.7.7.7,string3,comment3
2.2.2.2,string2,comment2
88.88.88.88,string4,comment4
999.999,999,999,string5,comment5

The second file, file2.txt, contains strings that can appear in the first column of file1.txt. I need to remove the whole row in file1.txt if its first column's string appears in file2.txt. Please note that I do not want to change th original file, but I want to put the output in a new file.

1
  • 1
    If you don't need to restrict the match to the first column of file1.txt specifically, then probably something like grep -vFf file2.txt file1.txt > newfile should do Oct 7, 2018 at 23:01

2 Answers 2

1

Why not simply

grep -vffile2 file1
-f FILE: Obtain patterns from FILE, one per line.
-v:      Invert the sense of matching, to select non-matching lines.
0

You can try something like

#!/bin/bash 
cat file2.txt | while IFS=, read line; do

sed -i "/$(grep $line file1.txt)/d" file1.txt

done

Be aware that sed -i will make direct changes to file1.txt, but you can change the command to sed -i.ibk in order to save a backup copy of the original file.

For example

$cat file2.txt 
1.1.1.1
7.7.7.7

$cat file1.txt 
1.1.1.1,string1,comment1
7.7.7.7,string3,comment3
2.2.2.2,string2,comment2
88.88.88.88,string4,comment4
999.999,999,999,string5,comment5

output 
2.2.2.2,string2,comment2
88.88.88.88,string4,comment4
999.999,999,999,string5,comment5
1
  • In order to make sure the result is correct, sed can be used on its own without the i so that the changes are only sent to stdout. Oct 7, 2018 at 23:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .