2012-11-20 40 views
9

我有一個像一個單獨的行

句子每個單詞這是例如

我想寫這樣一個文件,以便在這個句子中每個字被寫入到一個單獨的線。

如何在shell腳本中執行此操作?

回答

8

嘗試使用:

string="This is for example" 

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

或服用優勢字拆分

string="This is for example" 

for word in $string; do 
    echo "$word" 
done > filename.txt 
+0

謝謝!我希望將其寫入文件。怎麼做? –

+0

根據編輯 –

+0

您可以在循環版本中使用單個I/O重定向,其中包含'done> filename.txt'(它確保文件被截斷並且只包含'$ string'中的數據,而'>>'註釋會使'filename.txt'的任何以前的內容保持不變,並且在最後附加新的材料 –

5
example="This is for example" 
printf "%s\n" $example 
+0

單行:'printf「%s \ n」這是例子 – kenorb

13

一對夫婦的方式去它,選擇自己喜歡的!

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

或者乾脆這樣做是爲了避免使用echo不必要的:

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

<<<符號使用帶有herestring

或者,使用sed代替tr

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

對於仍然更多的選擇,檢查別人的答案=)

2

嘗試使用:

str="This is for example" 
echo -e ${str// /\\n} > file.out 

輸出

> cat file.out 
This 
is 
for 
example 
11
$ echo "This is for example" | xargs -n1 
This 
is 
for 
example