macossed

More than one number or 'g' in substitute flags


When I use sed in mac OS, I can't use substitute flags like this:

sed 's/xx/yy/3g' my.txt 

What's the replacement for this command? I cannot use "3g" together here. This use case is in the reference documentation.

When I use BSD sed, it shows an error:

more than one number or 'g' in substitute flags

Solution

  • This might work for you (GNU sed):

    sed 's/x/\ny/3;h;s/x/y/g;H;g;s/\n.*\n//' file
    

    Place a unique marker after the occurences you want to preserve, copy the line to the hold space (HS), replace all occurences then append these to the copy and remove the chunk between the two unique markers.

    This method should be accomodated by most sed's. If the sed your using does not handle \n's then use a unique string e.g. @@a unique string @@