简体   繁体   English

使用awk将一行分成多行

[英]Chop a row into multiple rows using awk

I am trying to chop a line into multiple lines using awk. 我正在尝试使用awk将一条线切成多行。 After every two words. 每两个字之后。

Input: 输入:

hey there this is a test 

Output: 输出:

hey there
this is
a test

I am able to achieve it using xargs ,as follow: 我可以使用xargs实现它,如下所示:

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

However I am curious to know how to achive this using awk. 但是我很好奇如何使用awk实现这一点。 Here is command I am using, which of course didn't gave expected result. 这是我正在使用的命令,当然没有给出预期的结果。

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

And

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

Need to know what is conceptually wrong in above awk command and how it can be modified to give correct output. 需要知道上述awk命令在概念上有什么错误以及如何对其进行修改以提供正确的输出。 Assume input is of single line. 假设输入为单行。

Thanks and Regards. 谢谢并恭祝安康。

Using awk you can do: 使用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

First you want OFS (field separator) not ORS (record separator). 首先,您要OFS(字段分隔符)而不是ORS(记录分隔符)。 And your for is in the end setting a single ORS, it iterates over all fields and sets the ORS value back and forth between " " and "\\n" and at the end only one value will be there. 您的最终目的是设置一个ORS,然后在所有字段上进行迭代,并在“”和“ \\ n”之间来回设置ORS值,最后只有一个值。

So what you really want is to operate on records (normally those are lines) instead of fields (normally spaces separate them). 因此,您真正想要的是对记录(通常是行)而不是字段(通常将它们分隔开)进行操作。

Here's a version that uses records: 这是使用记录的版本:

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

Result: 结果:

hey there
this is
a test

Another flavour of @krzyk's version: @krzyk版本的另一种风味:

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

$

Maybe even: 甚至会:

awk 'BEGIN {RS=" "} {ORS=(ORS==RS?"\n":RS)} 1' test.in

They both do leave an ugly enter in the end, though. 不过,他们俩最终都留下了丑陋的入口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM