2016-08-05 340 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 

他們都做留在最後一個醜陋的進入,雖然。