简体   繁体   中英

How to find and erase lines inside a text file

I have two text files:

remove.txt

red
green
blue

collors.txt

yellow
red
black
green
grey
blue

I want to remove the occurrences of remove.txt lines inside collors.txt and save it as output.txt . I tried using sed command inside a loop, but couldn't make it work.

Script:

remove='remove.txt'
input='collors.txt'
while read line; do
    # I failed to use sed here to do the job
done < $remove

No need to use a Unix tool, cmd can do it itself:

findstr /v /x /g:remove.txt collors.txt > output.txt

See the output of findstr /? to learn about the switches

Output with your example files:

yellow
black
grey

This might work for you (GNU sed):

sed 's#.*#/&/d#' removeFile | sed -f - coloursFile >outFile

Create a sed script from the removeFile and apply it to the coloursFile to produce the outFile. The created script will have a line like /colour/d for each line in the remove file where the colour will be replaced by red etc.

NB The -f - option applies the output from the previous pipe as an input sed script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM