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

时间:2014-07-22 22:47:55

标签: 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  

我需要的是:

    cat output.txt 


   ZYY   -2.4   138      #Need the entire lines removed that matched the 3rd column string DNW
   ZZZ   -3.4   200

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

谢谢!

P.S。我会对主要使用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!

欢呼并感谢所有的帮助!

4 个答案:

答案 0 :(得分:4)

grepsed

更容易
grep -v DNW sample.txt >> output.txt

如果你想在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)

或者,如果你想要它更简洁(但新手可能更难理解):

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

答案 1 :(得分:3)

你得到的几乎是正确的:

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

答案 2 :(得分:0)

你的sed命令在OSX上适用于我。尝试超级明确并试试这个:

sed '/^.*DNW.*$/d' sample.txt >> output.txt

答案 3 :(得分:0)

您也可以使用awk

awk '!/DNW/' file
   ZYY   -2.4   138
   ZZZ   -3.4   200