2016-08-05 5 views
2

awkを使用して複数の行に行を切り詰めようとしています。 2単語ごとに。awkを使用して行を複数の行に分割する

入力:

hey there this is a test 

出力:私はxargsのを使用して、それを達成することができています

hey there 
this is 
a test 

、次のように:

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

は、しかし、私は好奇心がachiveする方法を知っていますこれは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コマンドで間違ったとどのように正しい出力を与えるように変更することが可能であるかを知る必要があります。入力が1行であると仮定します。

ありがとうございます。

答えて

3

:@のkrzykのバージョンの

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を設定し、すべてのフィールドを反復し、ORS値を ""と "\ n"の間で前後に設定し、最後には1つの値だけがそこにあります。

本当に必要なのは、フィールド(通常はスペースで区切られたもの)の代わりにレコード(通常は行です)で操作することです。

ここでレコードを使用したバージョンです:

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

結果:あなたができるのawkを使用して

hey there 
this is 
a test 
+0

ありがとうございました。 –

1

別の味:

は、
$ 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 

どちらもかかわらず、最後に入力した醜いを残してください。

関連する問題