0

I already tried using sed, now I'm using tr,

list="banana, apple, orange, strawberry"

listed_text=$(echo $list| tr , '\n')

Desired output:

banana
apple
orange
strawberry

Output I get:

banana apple orange strawberry

I'm using zsh as shell, but I checked in bash and it also doesn't work. I tried \n, \n, tried an literal newline "\ " but it won't work. All I get is t that same single line output!

  • 1
    What do you mean by "actual output". The commands you present would produce no output at all. `echo "$listed_text"` should give you what you expect, however, while `echo $listed_text` would give you what you claim you are getting. – William Pursell May 28 '22 at 20:33
  • BTW, the proper bash way to store a list of things is in an _array_. If you used `IFS=', ' read -r -a items <<<"$list"`, then you'd have a proper list of your items; you could use `echo "Number of items is ${#items[@]}"` to count the entries; `echo "${items[0]}"` or `echo "$items"` to show only the first one, `printf '%s\n' "${items[@]}"` to print them all, etc. – Charles Duffy May 28 '22 at 20:42

1 Answers1

0

Using (tr is not sufficient to remove leading space):

echo "$list" | sed 's/, /\n/g'
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223