Home > Net >  Reading array in a loop and ignoring spaces in favor of a newline
Reading array in a loop and ignoring spaces in favor of a newline

Time:07-29

I am trying to load a variable '$LIST' that contains an array using the 'for' loop. However, I don't want them to be separated at spaces, but at the point of a new line. How can I get this effect?

LIST=( \
"1" "Some text" "ON" \
"2" "Some text" "OFF" \
"3" "Some text. Some text" "ON" \
"4" "Some text" "OFF" \
"5" "Some text. Some text" "OFF" \
)

for ENTRY in "${LIST[@]}"
do
    echo "$ENTRY"
done

I currently gets the following result:

1
Some text
ON
2
Some text
OFF
3
Some text. Some text
ON
4
Some text
OFF
5
Some text. Some text
OFF

And I would like to get this:

1 Some text ON
2 Some text OFF
3 Some text. Some text ON
4 Some text OFF
5 Some text. Some text OFF

CodePudding user response:

Put each line in quotes, not each word.

LIST=( 
"1 Some text ON" 
"2 Some text OFF"
"3 Some text. Some text ON" 
"4 Some text OFF" 
"5 Some text. Some text OFF" 
)

CodePudding user response:

First of all you don't need to use line continuation back-slashes \ to arrange the declaration of your list array.

Next, non exported variables are best entirely lower-case.

To iterate your list/array by groups of 3 element; passing the array elements as arguments to a function allows to do what you want.

#!/bin/bash

list=(
  "1" "Some text" "ON"
  "2" "Some text" "OFF"
  "3" "Some text. Some text" "ON"
  "4" "Some text" "OFF"
  "5" "Some text. Some text" "OFF"
)

do_output () {
  # iterates while there are still arguments
  while [ $# -gt 0 ]
  do
    # prints 3 arguments
    printf '%s %s %s\n' "$1" "$2" "$3"
    # shifts to the next 3 arguments
    shift 3
  done
}

do_output "${list[@]}"
  • Related