Sed substitute recursively

前端 未结 6 876
我在风中等你
我在风中等你 2020-12-28 18:35

echo ddayaynightday | sed \'s/day//g\'

It ends up daynight

Is there anyway to make it substitute until no more match ?

6条回答
  •  醉酒成梦
    2020-12-28 19:15

    The following works:

    $ echo ddayaynightday | sed ':loop;/day/{s///g;b loop}'
    night
    

    Depending on your system, the ; may not work to separate commands, so you can use the following instead:

    echo ddayaynightday | sed -e ':loop' -e '/day/{s///g
                                                   b loop}'
    

    Explanation:

    :loop       # Create the label 'loop'
    /day/{      # if the pattern space matches 'day'
      s///g     # remove all occurrence of 'day' from the pattern space
      b loop    # go back to the label 'loop'
    }
    

    If the b loop portion of the command is not executed, the current contents of the pattern space are printed and the next line is read.

提交回复
热议问题