2

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!

0

5 Answers 5

5

A file bla:

a b c d e 

Using sed:

sed 's/\s\+/\n/g' bla 

Results in:

a b c d e 
Sign up to request clarification or add additional context in comments.

2 Comments

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)
Thank you Kabanus, yours was also really nice and helpful.
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.

2 Comments

Thank you Jack it was really helpful, especially knowing how to get a back up from the original file.
Than why don't you accept his solution? The V on the left.
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 

Comments

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 

2 Comments

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.
I am actually really intrigued that your suggestion is using awk. I could never thought of awk for this problem.
0

If Perl is an option:

echo "a b c d e" | perl -pe 's/\s+/\n/g' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.