2016-08-05 335 views
2

我试图用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

使用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 
+0

谢谢,工作。 –

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 

他们都做留在最后一个丑陋的进入,虽然。