Martin
Martin

Reputation: 1197

add trailing newlines to all bash array items but the last one

I have an array called "array" which contains five animal names. I would like to have two newlines(\n\n) after each array item expect the last one. Script below does exactly what I want:

[user@T60 ~]$ cat scriptfile.sh 
#!/usr/bin/env bash

array=( cat dog elefant zebra hippo )

number_of_items_in_array=${#array[@]}

penultimate_array_item=$(( $number_of_items_in_array - 2 ))

ultimate_array_item=$(( $number_of_items_in_array - 1 ))

for i in $(seq 0 $penultimate_array_item); do
    printf '%s\n' "${array[$i]/%/$'\n\n'}"
done

for i in $ultimate_array_item; do
    printf '%s\n' "${array[$i]}"
done

[user@T60 ~]$ ./scriptfile.sh 
cat


dog


elefant


zebra


hippo
[user@T60 ~]$ 

However, I find it bit clunky. Is there a more elegant and minimalistic solution?

Upvotes: 0

Views: 2551

Answers (3)

ruakh
ruakh

Reputation: 183564

You can write:

array=( cat dog elefant zebra hippo )
echo "$(printf '%s\n\n\n' "${array[@]}")"

Notes:

  • If you give printf more arguments than the format-string refers to, then it just re-processes the format-string over and over again until it's used up all its arguments. So the above printf prints each array-element followed by two newlines.
  • Command-substitution, "$(...)", strips off all trailing newlines, even though it leaves other whitespace intact.

Upvotes: 6

Gordon Davisson
Gordon Davisson

Reputation: 126048

Combining @glenn jackman's insight about printing two newlines before each element except the first one with bash's array slicing capability:

printf "%s\n" "${array[0]}"
printf "\n\n%s\n" "${array[@]:1}"

(Note that this won't work right if the array only has one element.)

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247192

Your question worded differently: "I want to have two newlines printed before each element except the first one."

prefix=""
for element in "${array[@]}"; do
    printf "%s%s\n" "$prefix" "$element"
    prefix=$'\n\n'
done

Upvotes: 1

Related Questions