How to make sed remove lines not matched by a substitution

前端 未结 4 1974
生来不讨喜
生来不讨喜 2020-12-10 10:22

I basically want to do this:

cat file | grep \'\' | sed \'s///g\'

without having to

相关标签:
4条回答
  • 2020-12-10 10:58

    This might work for you:

    sed '/<expression>/!d;s//<replacement>/g' file
    

    Or

    sed 's/<expression>/<replacement>/gp;d' file
    
    0 讨论(0)
  • 2020-12-10 11:20
    cat file | sed -n '/<expression>/{s//<replacement>/g;p;}'
    
    0 讨论(0)
  • 2020-12-10 11:20

    How about:

    cat file | sed 'd/<expression>/'
    

    Will delete matching patterns from the input. Of course, this is opposite of what you want, but maybe you can make an opposite regular expression?

    Please not that I'm not completely sure of the syntax, only used it a couple of times some time ago.

    0 讨论(0)
  • 2020-12-10 11:22

    Say you have a file which contains text you want to substitute.

    $ cat new.text 
    A
    B
    

    If you want to change A to a then ideally we do the following -

    $ sed 's/A/a/' new.text 
    a
    B
    

    But if you don't wish to get lines that are not affected with the substitution then you can use the combination of n and p like follows -

    $ sed -n 's/A/a/p' new.text 
    a
    
    0 讨论(0)
提交回复
热议问题