Linux 在bash中,如何将一列拆分为多个固定维度的列
如何将单个列拆分为固定维度的多个列,例如,我有一个这样的列:Linux 在bash中,如何将一列拆分为多个固定维度的列,linux,bash,shell,Linux,Bash,Shell,如何将单个列拆分为固定维度的多个列,例如,我有一个这样的列: 1 2 3 4 5 6 7 8 尺寸p。例4,我想获得 1 5 2 6 3 7 4 8 1 3 5 7 2 4 6 8 1 5 2 6 3 7 4 8 1 3 5 7 2 4 6 8 或者是p码的。例2,我想获得 1 5 2 6 3 7 4 8 1 3 5 7 2 4 6 8 1 5 2 6 3 7 4 8 1 3 5 7 2 4 6 8 如果您知道所需的输出宽度,可以使用列 # Display in columns
1
2
3
4
5
6
7
8
尺寸p。例4,我想获得
1 5
2 6
3 7
4 8
1 3 5 7
2 4 6 8
1 5
2 6
3 7
4 8
1 3 5 7
2 4 6 8
或者是p码的。例2,我想获得
1 5
2 6
3 7
4 8
1 3 5 7
2 4 6 8
1 5
2 6
3 7
4 8
1 3 5 7
2 4 6 8
如果您知道所需的输出宽度,可以使用
列
# Display in columns for an 80 column display
cat file | column -c 80
使用awk:
awk '
BEGIN {
# Numbers of rows to print
n=4;
}
{
# Add to array with key = 0, 1, 2, 3, 0, 1, 2, ..
l[(NR-1)%n] = l[(NR-1)%n] " " $0
};
END {
# print the array
for (i = 0; i < length(l); i++) {
print l[i];
}
}
' file
awk'
开始{
#要打印的行数
n=4;
}
{
#添加到键为0,1,2,3,0,1,2,…的数组中。。
l[(NR-1)%n]=l[(NR-1)%n]“”$0
};
结束{
#打印阵列
对于(i=0;i
好的,这有点冗长,并非绝对正确,但以下几点应该有效:
td=$( mktemp -d ); split -l <rows> <file> ${td}/x ; paste $( ls -1t ${td}/x* ) ; rm -rf ${td}; unset td
创建一个临时目录,以便我们可以将临时文件放入其中。将其存储在td
中-您的shell可能已经有了td
变量,但是如果您为其创建了子shell,那么您的范围应该是正常的
split -l <rows> <file> f ${td}/x
写出这些文件,使行在连续的列中
rm -rf ${td}
删除文件和目录
unset td
清洁环境。假设您知道列中的行数(此处为8):
请参阅,了解如何执行相反的操作,即在给定指定列数的情况下生成多行。@Thomas我尝试过pr,折叠而不折叠success@rgnomeId如果我有一个从1到40的列,并且我想分成几列,它就不起作用了,每个包含10个元素的元素都是固定大小的输入项?@rgnome我尝试过使用数字为1到40的列
$ cat tst.awk
{ a[NR] = $0 }
END {
OFS=","
numRows = (numRows ? numRows : 1)
numCols = ceil(NR / numRows)
for ( rowNr=1; rowNr<=numRows; rowNr++ ) {
for ( colNr=1; colNr<=numCols; colNr++ ) {
idx = rowNr + ( (colNr - 1) * numRows )
printf "%s%s", a[idx], (colNr<numCols ? OFS : ORS)
}
}
}
function ceil(x, y){y=int(x); return(x>y?y+1:y)}
$ awk -v numRows=2 -f tst.awk file
1,3,5,7
2,4,6,8
$ awk -v numRows=4 -f tst.awk file
1,5
2,6
3,7
4,8
$ seq 10 | awk -v numRows=4 -f tst.awk
1,5,9
2,6,10
3,7,
4,8,