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

后端 未结 18 2150
生来不讨喜
生来不讨喜 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:29

    Curiously enough, the accepted answer does not actually answer the question directly. The question asks about using sed to replace a string, but the answer seems to presuppose knowledge of how to convert an arbitrary string into a regex.

    Many programming language libraries have a function to perform such a transformation, e.g.

    python: re.escape(STRING)
    ruby: Regexp.escape(STRING)
    java:  Pattern.quote(STRING)
    

    But how to do it on the command line?

    Since this is a sed-oriented question, one approach would be to use sed itself:

    sed 's/\([\[/({.*+^$?]\)/\\\1/g'
    

    So given an arbitrary string $STRING we could write something like:

    re=$(sed 's/\([\[({.*+^$?]\)/\\\1/g' <<< "$STRING")
    sed "/$re/d" FILE
    

    or as a one-liner:

     sed "/$(sed 's/\([\[/({.*+^$?]\)/\\\1/g' <<< "$STRING")/d" 
    

    with variations as described elsewhere on this page.

提交回复
热议问题