Naveen Thota
Naveen Thota

Reputation: 9

Print each word on different line which are separated by comma

I want to print different words in different rows which are separated by the comma using bash script.

ent0
ent4
ent1,ent5
ent2,ent6
ent3,ent7
ent29,ent30

I want to print each word in different line.

Upvotes: 0

Views: 1428

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84541

If I understand your question, you can do it quite simply with IFS, printf and command substitution, e.g.

$ IFS="$IFS,"; printf "%s\n" $(<file.txt)
ent0
ent4
ent1
ent5
ent2
ent6
ent3
ent7
ent29
ent30

(don't forget to reset IFS to its default $' \t\n' (space tab newline) when done. You can save oldifs="$IFS", then run your command, and set IFS="$oldifs" afterwards as an easy reset)

Upvotes: 0

Anubis
Anubis

Reputation: 7435

Using tr,

echo 'ent0 ent4 ent1,ent5 ent2,ent6 ent3,ent7 ent29,ent30' | tr ',' '\n'

Using sed,

echo 'ent0 ent4 ent1,ent5 ent2,ent6 ent3,ent7 ent29,ent30' | sed 's/,/\n/g'

Both will produce,

ent0 ent4 ent1
ent5 ent2
ent6 ent3
ent7 ent29
ent30

EDIT:

Your requirement is not clear enough. If you want to split by both commas and spaces,

echo 'ent0 ent4 ent1,ent5 ent2,ent6 ent3,ent7 ent29,ent30' | tr ', ' '\n'

or

echo 'ent0 ent4 ent1,ent5 ent2,ent6 ent3,ent7 ent29,ent30' | sed 's/\(,\| \)/\n/g;'

This will produce,

ent0
ent4
ent1
ent5
ent2
ent6
ent3
ent7
ent29
ent30

If the content is in a file, say input.txt, use it instead of echo.

tr ', ' '\n' <input.txt

Upvotes: 2

Related Questions