如何在shell脚本中获得以下结果?
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
...
...
期望的输出:
This is line 1 This is line 2 This is line 3
This is line 4 This is line 5 This is line 6
This is line 7 This is line 8 This is line 9
... ... ....
... ... ...
答案 0 :(得分:9)
awk
是你的朋友:
$ awk 'ORS=NR%3?FS:RS' file
This is line 1 This is line 2 This is line 3
This is line 4 This is line 5 This is line 6
This is line 7 This is line 8 This is line 9
与以下内容相同:
$ awk 'ORS=NR%3 ? " " : "\n"' file
This is line 1 This is line 2 This is line 3
This is line 4 This is line 5 This is line 6
This is line 7 This is line 8 This is line 9
如果记录数不是3的倍数,则将输出记录分隔符设置为空格;否则,作为新行。
ORS
定义输出记录分隔符。NR
定义记录数(本例中为行)。FS
定义字段分隔符。默认值为" "
(空格)。RS
定义记录分隔符。默认值为"\n"
(新行)。Idiomatic awk中的更多信息和相关示例。
答案 1 :(得分:4)
试试这个,
paste -d " " - - - < file
此空格作为分隔符的粘贴命令将3个连续的行组合成一行。
答案 2 :(得分:1)
sed version
sed -e '$ b print
N
$ b print
N
:print
s/\n/ /g' YourFile
如果只有3行中的多行,则$ b print
和:print
不是必需的
在一个行版本
非GNU sed(就像我的AIX)
sed -e '$bprint' -e 'N;$bprint' -e 'N;:print' -e 's/\n/ /g' YourFile
对于GNU sed(没有经过测试,在这里缺少linux)
sed -e '$bprint;N;$bprint;N;:print;s/\n/ /g' YourFile
答案 3 :(得分:1)
这可能适合你(GNU sed):
sed '$!N;$!N;y/\n/ /' file