How to delete from a text file, all lines that contain a specific string?

后端 未结 18 2140
生来不讨喜
生来不讨喜 2020-11-22 02:06

How would I use sed to delete all lines in a text file that contain a specific string?

18条回答
  •  北海茫月
    2020-11-22 02:39

    There are many other ways to delete lines with specific string besides sed:

    AWK

    awk '!/pattern/' file > temp && mv temp file
    

    Ruby (1.9+)

    ruby -i.bak -ne 'print if not /test/' file
    

    Perl

    perl -ni.bak -e "print unless /pattern/" file
    

    Shell (bash 3.2 and later)

    while read -r line
    do
      [[ ! $line =~ pattern ]] && echo "$line"
    done  o
    mv o file
    

    GNU grep

    grep -v "pattern" file > temp && mv temp file
    

    And of course sed (printing the inverse is faster than actual deletion):

    sed -n '/pattern/!p' file
    

提交回复
热议问题