Skip to content
Advertisement

Bash – delete rows from one file while iterating through rows from another file

I have two files.

file.txt and delete.txt

file.txt contains the following for ex.:

/somedirectory/
/somedirectory2/somefile.txt
/anotherfile.txt

delete.txt contains:

/somedirectory/
/somedirectory2/somefile.txt

I need to delete the rows from file.txt that are contained within delete.txt

cat file.txt should result with:

/anotherfile.txt

So far I’ve tried this with no luck:

while read p; do
    line=$p;
    sed -i '/${line}/d' file.txt;
done < delete.txt

I don’t receive any error, it just doesn’t edit my file.txt file. I’ve tested the while loop with an echo ${line} and it works as expected in that scenario.

Any suggestions?

Note: the while loop above doesn’t work as expected even when I took the forward slashes off of the files.

Advertisement

Answer

With a simple grep:

grep -vFxf  delete.txt file.txt > temp.txt && mv temp.txt file.txt 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement