将每N行输入放入新列 [英] Put every N rows of input into a new column

查看:77
本文介绍了将每N行输入放入新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中,给定输入

In bash, given input

1
2
3
4
5
6
7
8
...

还有N例如5,我想要输出

And N for example 5, I want the output

1  6  11
2  7  12
3  8  ...
4  9
5  10 

我该怎么做?

推荐答案

在下面的脚本中用您的号码替换5.

replace 5 in following script with your number.

seq 20|xargs -n5| awk '{for (i=1;i<=NF;i++) a[i,NR]=$i; }END{
    for(i=1;i<=NF;i++) {for(j=1;j<=NR;j++)printf a[i,j]" "; print "" }}' 

输出:

1 6 11 16 
2 7 12 17 
3 8 13 18 
4 9 14 19 
5 10 15 20

上面的

注意seq 20只是用于生成要测试的数字序列.您在实际工作中不需要它.

note seq 20 above there is just for generating the number sequence for testing. You don't need it in your real work.

编辑

如sudo_O所指出的,我添加了一个纯awk解决方案:

as pointed out by sudo_O, I add an pure awk solution:

 awk -vn=5 '{a[NR]=$0}END{ x=1; while (x<=n){ for(i=x;i<=length(a);i+=n) printf a[i]" "; print ""; x++; } }' file

测试

kent$  seq 20| awk -vn=5 '{a[NR]=$0}END{ x=1; while (x<=n){ for(i=x;i<=length(a);i+=n) printf a[i]" "; print ""; x++; } }'     
1 6 11 16 
2 7 12 17 
3 8 13 18 
4 9 14 19 
5 10 15 20 

kent$  seq 12| awk -vn=5 '{a[NR]=$0}END{ x=1; while (x<=n){ for(i=x;i<=length(a);i+=n) printf a[i]" "; print ""; x++; } }'     
1 6 11 
2 7 12 
3 8 
4 9 
5 10 

这篇关于将每N行输入放入新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆