0

I only see spaces, no new lines.

script.sh:

STRING=$(echo "alpha,beta,gamma,delta" | tr "," "\n")
echo $STRING > string.txt

Result:

$ cat string.txt
alpha beta gamma delta

Desired result

$ cat string.txt
alpha
beta
gamma
delta
Ryan
  • 14,682
  • 32
  • 106
  • 179
  • Possible Duplicate: http://stackoverflow.com/questions/15184358/how-to-avoid-bash-command-substitution-to-remove-the-newline-character – Nehal J Wani May 02 '14 at 20:36
  • @NehalJ.Wani Is it really a duplicate of the question you linked? – gniourf_gniourf May 02 '14 at 20:58
  • If you want to have fun, you can always set `IFS` to nothing as: `IFS=''`. Then it works. Haha. Of course, the answer to your problem is to quote your variables. Use More Quote as some would say. – gniourf_gniourf May 02 '14 at 21:01
  • possible duplicate of [bash line concatenation during variable interpolation](http://stackoverflow.com/questions/3445628/bash-line-concatenation-during-variable-interpolation) – devnull May 03 '14 at 04:24

2 Answers2

4

Try quoting the $STRING variable:

echo "$STRING" > string.txt

e.g:

$ STRING=$(echo "alpha,beta,gamma,delta" | tr "," "\n")
$ echo $STRING
alpha beta gamma delta
$ echo "$STRING"
alpha
beta
gamma
delta
$ 
Digital Trauma
  • 15,475
  • 3
  • 51
  • 83
3

BASH / shell doesn't usually work right without quoting, make sure to use it here to get new lines in your file:

echo "$STRING" > string.txt

See official manual on world splitting (Thanks to Glenn)

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    A little deeper explanation than "cannot usually work right" would help, perhaps a link to ["Word splitting" in the manual](http://www.gnu.org/software/bash/manual/bashref.html#Word-Splitting) -- "The shell scans the results of parameter expansion, command substitution, and arithmetic expansion *that did not occur within double quotes* for word splitting." (emphasis mine) – glenn jackman May 02 '14 at 20:50