14

Why does echo ,,, |sed s':\(,\)\(,\):\1*\2:'g yield ",*,," rather than ",*,*,"? In other words: why, despite the "g" flag, does sed not insert '*' between one pair of commas?

14

Because with the two ,s in (,\)\(,\), you have already matched the first two ,s and the Regex pattern matched so far won't backtrack for the rest of the line. Only one is left now that is the last , hence it just printed as it is without any * in between it the second last one.

If you have another , in input, you would get the desired (global, g) response:

% echo ,,,, | sed s':\(,\)\(,\):\1*\2:'g
,*,,*,
| improve this answer | |
  • What's with the weird quotation? (Why leave s and g out of the quote marks?) – GnP Sep 6 '16 at 22:49
  • @GnP Haha, that's inherited from the OP. – heemayl Sep 6 '16 at 23:46
  • or echo ,,,,, |sed s':\(,\)\(,\):\1*:’g – njboot Sep 7 '16 at 7:26
8

The why of the question been already answered by @heemayl

Workaround with sed (here assuming GNU sed) - loop recursively as long as a match is found

$ echo ,,, | sed -E ':a s/(,)(,)/\1*\2/ ; ta'
,*,*,

$ echo ,,,, | sed -E ':a s/(,)(,)/\1*\2/ ; ta'
,*,*,*,

POSIXly:

$ echo ,,,, | sed -e :a -e 's/\(,\)\(,\)/\1*\2/; ta'
,*,*,*,

Or with perl

$ echo ,,, | perl -pe 's/,\K(?=,)/*/g'
,*,*,

$ echo ,,,, | perl -pe 's/,\K(?=,)/*/g'
,*,*,*,
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.