Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Each word on a separate line

Tags:

bash

shell

I have a sentence like

This is for example

I want to write this to a file such that each word in this sentence is written to a separate line.

How can I do this in shell scripting?

like image 629
Nathan Pk Avatar asked Nov 20 '12 21:11

Nathan Pk


3 Answers

A couple ways to go about it, choose your favorite!

echo "This is for example" | tr ' ' '\n' > example.txt

or simply do this to avoid using echo unnecessarily:

tr ' ' '\n' <<< "This is for example" > example.txt

The <<< notation is used with a herestring

Or, use sed instead of tr:

sed "s/ /\n/g" <<< "This is for example" > example.txt

For still more alternatives, check others' answers =)

like image 158
sampson-chen Avatar answered Oct 16 '22 05:10

sampson-chen


$ echo "This is for example" | xargs -n1
This
is
for
example
like image 31
Sepero Avatar answered Oct 16 '22 05:10

Sepero


Try using :

string="This is for example"

printf '%s\n' $string > filename.txt

or taking advantage of bash word-splitting

string="This is for example"

for word in $string; do
    echo "$word"
done > filename.txt
like image 9
Gilles Quenot Avatar answered Oct 16 '22 04:10

Gilles Quenot