2012-11-20 29 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