简体   繁体   English

每5个条目后分隔一行 - awk

[英]Split a column in lines after every 5 entries - awk

I have a file that looks like the following 我有一个如下所示的文件

1
1
1
1
1
1
12
2
2
2
2
2
2
2
3
4

What I want to do is convert this column in multiple rows. 我想要做的是将该列转换为多行。 Each new line/row should start after 5 entries, so that the output will like like this 每个新行/行应该在5个条目之后开始,因此输出将像这样

1 1 1 1 1
1 12 2 2 2
2 2 2 2 3
4

I tried to achieve that by using 我试图通过使用来实现这一点

awk '{printf "%s" (NR%5==0?"RS:FS),$1}' file

but I get the following error 但是我收到以下错误

awk: line 1: runaway string constant "RS:FS),$1} ...

Any idea on how to achieve the desired output? 有关如何实现所需输出的任何想法?

Maybe this awk one liner can help. 也许这个awk one liner可以提供帮助。

awk '{if (NR%5==0){a=a $0" ";print a; a=""} else a=a $0" "}END{print}' file

Output: 输出:

1 1 1 1 1
1 12 2 2 2
2 2 2 2 3
4

Longer awk: 更长的awk:

{
    if (NR%5==0)
    {
       a=a $0" ";
       print a;
       a="";
    }
    else
    {
       a=a $0" ";
    }
 }
 END
 {
    print
 }

Slightly different approach, still using awk: 稍微不同的方法,仍然使用awk:

$ awk '{if (NR%5) {ORS=""} else {ORS="\n"}{print " "$0}}' input.txt
 1 1 1 1 1
 1 12 2 2 2
 2 2 2 2 3
 4

Using perl : 使用perl

$ perl -p -e 's/\n/ / if $.%5' input.txt
1 1 1 1 1
1 12 2 2 2
2 2 2 2 3
4 

No need to complicate... 无需复杂化......

$ pr -5ats' ' <file

1 1 1 1 1
1 12 2 2 2
2 2 2 2 3
4

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

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