使用awk将行切成多行

时间:2016-08-05 09:54:08

标签: bash awk

我正在尝试使用awk将一条线切成多行。每两个字后。

输入:

hey there this is a test 

输出:

hey there
this is
a test

我可以使用xargs实现它,如下所示:

echo hey there this is a test |xargs -n2
hey there
this is
a test

但是我很想知道如何使用awk实现这个目标。这是我正在使用的命令,当然没有给出预期的结果。

echo hey there this is a test | awk '{ for(i=1;i<=NF;i++) if(i%2=="0") ORS="\n" ;else ORS=" "}1'
hey there this is a test

echo hey there this is a test | awk '{$1=$1; for(i=1;i<=NF;i++) if(i%2==0) ORS="\n" ;else ORS=" "}{ print $0}'
hey there this is a test

需要知道上面的awk命令在概念上是错误的,以及如何修改它以提供正确的输出。假设输入是单行的。

谢谢和问候。

3 个答案:

答案 0 :(得分:3)

使用awk你可以这样做:

s='hey there this is a test'
awk '{for (i=1; i<=NF; i++) printf "%s%s", $i, (i%2 ? OFS : ORS)}' <<< "$s"

hey there
this is
a test

答案 1 :(得分:2)

首先,你想要OFS(字段分隔符)而不是ORS(记录分隔符)。 并且你的for最终设置了一个ORS,它遍历所有字段并在“”和“\ n”之间来回设置ORS值,最后只有一个值。

所以你真正想要的是对记录(通常是那些是行)而不是字段(通常是空格分开它们)进行操作。

这是一个使用记录的版本:

echo hey there this is a test | awk 'BEGIN {RS=" "} {if ((NR-1)%2 == 0) { ORS=" "} else {ORS="\n"}}1' 

结果:

hey there
this is
a test

答案 2 :(得分:1)

@ krzyk的另一种版本:

$ awk 'BEGIN {RS=" "} {ORS="\n"} NR%2 {ORS=" "} 1' test.in
hey there
this is
a test

$

甚至可能:

awk 'BEGIN {RS=" "} {ORS=(ORS==RS?"\n":RS)} 1' test.in
但是,他们最终都会留下一个难看的输入。