Limiting Bash array single line output

#!/bin/bash

PH=(AD QD QC 5H 6C 8C 7D JH 3H 3S)

echo ${PH[@]}

In the above array, how can I print to screen just the first 8 elements of ${PH[@]} and have the last 2 elements print just below the first line starting underneath AD?

I need to do this in order to save terminal window spacing for Bash Script.

Thanks in advance for any and all suggestions.

Cogiz

echo ${PH[@]:0:7}
echo ${PH[@]:8:9}

While this happens to work with the sample array provided, asking to print 9 elements starting with index 8 seems to be a strange way to print the last two elements of an array of 10 elements. If you want to print the 1st 7 elements of an array on one line and the last 2 elements of that array on a second line (no matter how many elements are in the array, you might want to try something more like:

echo ${PH[@]:0:7}
echo ${PH[@]:$((${#PH[@]} - 2))}

or, if there is any chance that any of those elements in your array might contain multiple adjacent spaces, might contain tabs, or might contain newlines that you want preserved in the output:

echo "${PH[@]:0:7}"
echo "${PH[@]:$((${#PH[@]} - 2))}"
1 Like

Thank you very much for all of your help and suggestions...it pointed me in the right direction.

I used the following in my script:

tput cup 4 10
echo ${PH[@]:0:24}
tput cup 6 10
echo ${PH[@]:24:48}

Why :48 ? for two elements?

With a recent bash, try

echo ${PH[@]: -2}
3H 3S

Surely printf is a better fit here:

$ PH=(AD QD QC 5H 6C 8C 7D JH 3H 3S)
$ printf "%s\n" "${PH[@]}"
AD
QD
QC
5H
6C
8C
7D
JH
3H
3S

printf keeps reusing the format until it runs out of data to print. It follows that more %s specifiers will print more fields:

$ printf "%s %s %s %s %s %s %s %s\n" "${PH[@]}"
AD QD QC 5H 6C 8C 7D JH
3H 3S      

This has the advantage over the above solutions that when your array becomes bigger you don't have to change it:

$ PH=(AD QD QC 5H 6C 8C 7D JH 3H 3S AF R3 T0)
$ printf "%s %s %s %s %s %s %s %s\n" "${PH[@]}"
AD QD QC 5H 6C 8C 7D JH
3H 3S AF R3 T0 

cogiz, I noticed that your final solution was to limit to 24 fields. 24 %s s are a lot to type but I think it will be the most practical solution to your problem.

Andrew

1 Like