1

Maybe this is a dumb question but I really can't work this out.

I just want to replace every space with a new line with this code.

echo "300.000" | sed 's/[.:;,"]/ & /g' | sed 's/ /\n/g'

But the result is this:

300n.n000

My colleague says that is should work. I am on a Mac if that makes any difference?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Friso Stolk
  • 81
  • 2
  • 9
  • 3
    `sed` is a line-based processor, it's hard for it to work with newlines. GNU `sed` supports newlines, but differs from BSD `sed`, which is what MacOS uses. You might want to look into using `tr` instead. – hnefatl Jan 14 '19 at 11:31
  • It [works](https://ideone.com/x6tIkg) in *GNU* `sed`. – Wiktor Stribiżew Jan 14 '19 at 11:31
  • Tip: `echo $SHELL` prints the path to the executable of the current shell. That way you can find out what shell you're actually using and don't need to use the rather inaccurate term "linux shell" (especially if your on a Mac). – sticky bit Jan 14 '19 at 11:32
  • 1
    See [Newlines in sed on Mac OS X](https://superuser.com/questions/307165/newlines-in-sed-on-mac-os-x). – Wiktor Stribiżew Jan 14 '19 at 11:53
  • @stickybit The user's shell has no direct bearing on what syntax their `sed` implementation supports. (You could say `dollars="300.000"; echo "${dollars/./$'\n.\n'}"` in Bash, though.) – tripleee Jan 14 '19 at 12:42
  • @tripleee: In this case yes, the particular shell might not make a difference. But in general it could and if it did "linux shell" isn't really helping to understand what environment is used. I've meant that in a more general fashion. – sticky bit Jan 14 '19 at 12:45
  • 4
    Possible duplicate of [sed not giving me correct substitute operation for newline with Mac - differences between GNU sed and BSD / OSX sed](https://stackoverflow.com/q/24275070/608639). Also see [Replace comma with newline in sed on MacOS?](https://stackoverflow.com/q/10748453/608639) and [Newlines in sed on Mac OS X](https://superuser.com/q/307165/173513) on [Super User](http://superuser.com/). – jww Jan 14 '19 at 18:35

1 Answers1

0

Unfortunately, newlines in sed are not completely standardized. On MacOS, the following works:

echo "300.000" | sed 's/[.:;,"]/\
&\
/g'

(Yes, those are literal, backslashed newlines inside single quotes.)

On those platforms where \n works, you could simplify to

echo "300.000" | sed 's/[.:;,"]/\n&\n/g'

If you want to replace all spaces, tr is a portable solution:

echo "300.000" | sed 's/[.:;,"]/ & /g' | tr ' ' '\012'

A more succinct solution might be to use Perl, which is not standardized at all, but only exists in a single implementation, so effectively works portably wherever Perl is installed:

echo "300.000" | perl -pe 's/[.:;,"]/\n$&\n/g'
tripleee
  • 175,061
  • 34
  • 275
  • 318