sed:如何删除匹配特定字符串的整行?

Nov*_*ice 2 bash sed

我在删除 sample.txt 中的整行时遇到问题

   cat sample.txt

   XYZ   -2.4   DNW
   ZYY   -2.4   138
   ZZZ   -3.4   200
   ZZZ   -2.4   DNW 

  sed '/DNW/d' sample.txt >> output.txt

  cat output.txt 

   XYZ   -2.4                 #removes the DNW, but not the entire line
   ZYY   -2.4   138
   ZZZ   -3.4   200
   ZZZ   -2.4  
Run Code Online (Sandbox Code Playgroud)

我需要的是这个:

    cat output.txt 


   ZYY   -2.4   138      #Need the entire lines removed that matched the 3rd column string DNW
   ZZZ   -3.4   200
Run Code Online (Sandbox Code Playgroud)

我是 bash 新手,想知道是否有选项可以删除与搜索条件匹配的文本文件中的整行?

谢谢!

ps 我会对主要使用 bash 的可能解决方案感兴趣。但是,我也开始使用 python,如果有解决方案,我也很乐意学习这些解决方案。

更新

事实证明,我的原始 sample.txt 文件格式不正确。以下解决了该问题,因为它将行更改为逗号分隔格式(例如,x、y、c = 被视为一行)。

   cp sample.txt sample.csv
   sed '/DNW/d' sample.csv > output.txt #Please note any of the below user suggested answers/solutions work!
Run Code Online (Sandbox Code Playgroud)

干杯和感谢所有的帮助!

Jak*_*ski 7

你几乎猜对了:

sed '/DNW/d' sample.txt >> output.txt


aba*_*ert 5

这甚至更容易grepsed

grep -v DNW sample.txt >> output.txt
Run Code Online (Sandbox Code Playgroud)

如果你想用 Python 来做,它会更冗长,但实际上并不难:

with open('sample.txt') as fin, open('output.txt', 'a') as fout:
    for line in fin:
        if 'DNW' not in line:
            fout.write(fin)
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望它更简短一些(但对于新手来说可能更难理解):

with open('sample.txt') as fin, open('output.txt', 'a') as fout:
    fout.writelines(line for line in fin if 'DNW' not in line)
Run Code Online (Sandbox Code Playgroud)