Is there a *nix command that formats input (delimited by newlines) so that only a specific max number of elements appear per line? For example:
$ 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
Arrays can be sliced.
$ foo=(q w e r t y u)
$ echo "${foo[@]:0:4}"
q w e r
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With