是否有 *nix 命令格式化输入(由换行符分隔),以便每行只出现特定的最大元素数?例如:
$ yes x | head -10 | command 4 x x x x x x x x x x
I wrote a quick bash
script (shown below) that performs this task, but it seems long and probably inefficient. Is there a better way to do this?
#!/bin/sh
if [ -z "$1" -o -z "$2" ]; then
echo Usage `basename $0` {rows} {columns}
exit 1
fi
ROWS=$1
COLS=$2
input=$(yes x | head -${ROWS})
lines=()
i=0
j=0
eol=0
for x in ${input[*]}
do
lines[$i]="${lines[$i]} $x"
j=`expr $j + 1`
eol=0
if [ $j -ge ${COLS} ]; then
echo lines[$i] = ${lines[$i]}
i=`expr $i + 1`
j=0
eol=1
fi
done
if [ ${eol} -eq 0 ]; then
echo lines[$i] = ${lines[$i]}
fi
最佳答案
printf '%-10s%-10s%-10s%s\n' $(command | command)
printf
将一次消耗格式字符串中指定的参数数量,并继续直到它们都被消耗掉。示范:
$ printf '%-10s%-10s%-10s%s\n' $(yes x | head -n 10)
x x x x
x x x x
x x
$ printf '%-10s%-10s%-10s%s\n' $(<speech)
now is the time
for all good men
to come to the
aid of their country
关于linux - bash:一次获取多个数组元素的更简单方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10669867/