Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: simpler way to get multiple elements of array at once?

Tags:

linux

bash

unix

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
like image 329
tony19 Avatar asked Oct 12 '25 15:10

tony19


1 Answers

Arrays can be sliced.

$ foo=(q w e r t y u)
$ echo "${foo[@]:0:4}"
q w e r
like image 148
Ignacio Vazquez-Abrams Avatar answered Oct 14 '25 06:10

Ignacio Vazquez-Abrams