In each line in I want to replace last two commas with dots

I found such two sed piped method but it does not work with sed on MacOS

$ echo 'abc,def,12379,foo' | sed 's/\(.*\),/\1./'|sed 's/\(.*\),/\1./'

Would there be a way which will work with any sed version? Not necessarily with sed only.

  • 2
    How does it fail on MacOS? – choroba Jan 11 '19 at 9:23
  • Can you add -e to the sed command? So like this: echo 'abc,def,12379,foo' | sed -e 's/\(.*\),/\1./'|sed -e 's/\(.*\),/\1./'. – rowan Jan 11 '19 at 9:29

Try this:

$ echo 'abc,def,12379,foo' | sed 's/,\([^,]*\),\([^,]*\)$/.\1.\2/'

This will leave lines with a single comma alone (eg foo,bar). That may or may not be what you want.

\(...\) capture groups and \1, \2 backrerefences in the replacement string should be supported in all versions of sed; I've tested the above on Unix v7.

PS. Even the double sed from your question should work on MacOS; maybe your problem is that the lines are terminated by CarriageReturns instead of LineFeeds?

echo 'abc,def,12379,foo' | sed -e 's/\(.*\),/\1./' -e 's/\(.*\),/\1./'


echo 'abc,def,12379,foo' | sed -e 's/\(.*\),/\1./;s/\(.*\),/\1./'

Using awk, treating the input as a set of comma-delimited fields, and joining the three last fields with dots,

echo 'abc,def,12379,foo' |
awk 'BEGIN { OFS=FS="," } { print $1, $2 "." $3 "." $4 }'

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.