每行打印一个字

Print one word per line

我几乎尝试了所有方法,sed、awk、tr,但是...

我正在尝试输出一个包含这个的文件

 2079 May 19 13:37 temp.sh
 1024 May 23 17:09 mirrad
 478 May 26 14:48 unzip.sh

像这样

 2079
 May
 19
 13:37
 .
 .
 .

因此每个字符串将在变量中一次打印一个。

我会继续回答这个问题,因为我用错误的重复问题标记了它。

使用tr:

echo "Mary had a little lamb" | tr ' ' '\n'

在上面的命令中,您将 ' ' 替换为换行符 '\n'

使用sed:

echo "Mary had a little lamb" | sed 's/ /\n/g'

如果您有多个空格要变成一个换行符,请改用 s/ */\n/g。即 / 后跟 两个 空格然后是 *.

awk

awk 'BEGIN{RS=" "} 1' file

输出

2079
May
19
13:37
temp.sh
1024
May
23
17:09
mirrad
478
May
26
14:48
unzip.sh

从文件中获取 printf 的参数:

printf "%s\n" $(<file)

另一个简单的衬里使用 xargs

xargs -n 1 <file

其中 -n 来自 man 页面的解释:-

-n max-args, --max-args=max-args
       Use at most max-args arguments per command line.  Fewer than
       max-args arguments will be used if the size (see the -s
       option) is exceeded, unless the -x option is given, in which
       case xargs will exit.

将产生输出

#!/bin/bash
$ xargs -n1 <tmp.txt
2079
May
19
13:37
temp.sh
1024
May
23
17:09
mirrad

-n 值为 2 它给出

#!/bin/bash     
$ xargs -n2 <tmp.txt
2079 May
19 13:37
temp.sh 1024
May 23
17:09 mirrad

备注

带有 xargs 的建议仅适用于 OP 中所示的简单输入。因此,该解决方案不适用于大文件(需要大量内存处理)或包含引号行的文件。请参阅涉及 awk 的其他答案。

只需一个 cattr 就可以轻松做到这一点

cat input.txt|tr ' ' "\n"

编辑:

更好的,没有UUOC

tr ' ' "\n" < input.txt

另一个awk

$ awk -v OFS='\n' '{=}1' file