I have text file which contains many words (strings) separated by a space. How can I replace the spaces by newlines. In other words, how can I have each string on a different line in bash
? I would be really grateful if one could also suggest a method using sed
!
Asked
Active
Viewed 7,219 times
1

James Brown
- 36,089
- 7
- 43
- 59

Armin
- 331
- 5
- 11
5 Answers
4
A file bla:
a b c d e
Using sed:
sed 's/\s\+/\n/g' bla
Results in:
a
b
c
d
e

James Brown
- 36,089
- 7
- 43
- 59

kabanus
- 24,623
- 6
- 41
- 74
-
Jack beat me to the punch so accept his answer. Note the way I wrote it outputs it to the terminal, while his method changes the file itself (with the bak) – kabanus Oct 21 '16 at 13:50
-
Thank you Kabanus, yours was also really nice and helpful. – Armin Oct 21 '16 at 14:24
2
Use the command:
sed -i.bak -e 's/\s\+/\n/g' file
\s
will match any whitespace character (spaces, tabs, newlines), and \+
will match on one or more occurrences in a row. -i.bak
will backup your original file to file.bak
.

Jack Bracken
- 1,233
- 12
- 23
-
Thank you Jack it was really helpful, especially knowing how to get a back up from the original file. – Armin Oct 21 '16 at 14:22
-
2
1
Few more ways:
$ cat ip.txt
foo bar baz
a 433 5er
cat fog try
using xargs
$ xargs -n1 < ip.txt
foo
bar
baz
a
433
5er
cat
fog
try
using grep
$ grep -o '[^ ]*' ip.txt
foo
bar
baz
a
433
5er
cat
fog
try

Sundeep
- 23,246
- 2
- 28
- 103
0
$ cat foo
a b c
1 2 3
In Gnu awk (and mawk):
$ awk -v RS=" +|\n" '{print $0}' foo
a
b
c
1
2
3
Using tr
for a single line:
$ tr -s \ '\n' <<< "a b c"
a
b
c

James Brown
- 36,089
- 7
- 43
- 59
-
Thank you James and sorry for repeating the questions, I had googled my question but the other question was replacing coma with newline, and well google could not help me finding the previous post. – Armin Oct 21 '16 at 14:26
-
I am actually really intrigued that your suggestion is using awk. I could never thought of awk for this problem. – Armin Oct 21 '16 at 14:27