Bash: an easy way to get multiple array elements at once?

Is there a * nix command that formats input (limited to newline characters), so that only a certain maximum number of elements are displayed on a line? For instance:

$ yes x | head -10 | command 4
xxxx
xxxx
xx

I wrote a quick bashscript (shown below) that performs this task, but 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
+3
source share
4 answers
printf '%-10s%-10s%-10s%s\n' $(command | command)

printf will consume the number of arguments specified in the format string, and continue until they are consumed.

Demonstration:

$ 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
+4
source

Arrays can be sliced.

$ foo=(q w e r t y u)
$ echo "${foo[@]:0:4}"
q w e r
+8
yes x | head -10 | awk 'BEGIN { RS = "%%%%%%%" } { split($0,a,"\n"); for (i=1; i<length(a); i+=4) print a[i], a[i+1], a[i+2], a[i+3] }'

:

yes x | \
head -10 | \
awk 'BEGIN { RS = "%%%%%%%" }
     { split($0,a,"\n"); 
       for (i=1; i<length(a); i+=4) print a[i], a[i+1], a[i+2], a[i+3] }'
+1

-

sed 's|\(.{10}\)|\1\n|'

Window . N .

PS Please correct sed statement for any syntax error.

0
source

All Articles