Sed command : how to replace if exists else just insert?

后端 未结 2 1167
无人及你
无人及你 2021-01-01 16:16

I need to edit several lines in a file such that if a line begins with (av or avpgw) then replace these with new text, else just insert the new text in beginning.

H

2条回答
  •  北海茫月
    2021-01-01 17:04

    You can do it this way:

    sed -e 's/^avpgw/new text/' -e t -e 's/^av/new text/' -e t -e 's/^/new text/' file
    

    This replaces the pattern with new text (s///) and jumps to the end (t). Otherwise it tries the next pattern. See also sed commands summary.

    You can also separate the commands with ;:

    sed 's/^avpgw/new text/; t; s/^av/new text/; t; s/^/new text/' file
    

    or put the commands in a sed command file:

    s/^avpgw/new text/
    t
    s/^av/new text/
    t
    s/^/new text/
    

    and call it this way:

    sed -f commandfile file
    

    If you want to ignore case, append an i at the end of the substitute command as in s/^av/new text/i. Another way is to spell it out with character sets s/^[aA][vV]/new text/. But that is not sed specific, for this you can search for regular expressions in general.

提交回复
热议问题