0

I have text and each line breaker, I store it the value in array and I display it :

var=("AAA
      aaa
      BBB
      bbb
      CCC
      ccc")

SAVEIFS=$IFS
 IFS=$'\n'
var=($var)
IFS=$SAVEIFS

for (( i=0; i<${#var[@]}; i++ )) do
  echo "${var[$i]}"
done

output :

   AAA
   aaa
   BBB
   bbb
   CCC
   ccc

but I want two first element in the same index array with the line breaker inside each element, like that

 var[0]=("AAA
         aaa")
  var[1]=("BBB
         bbb")
   var[2]=("CCC
         ccc")
2
  • Why is var an array when it has only a single element? Just use var=("AAA" "aaa" "BBB" "bbb" "CCC" "ccc"). If that string comes from an external source and you have to split it by line, use readarray -t var <<< "$str" instead of var=("$str"). Commented Feb 18, 2019 at 16:05
  • Then it's just a matter of array slicing. var2+=("${var[*]:i:2}") for i=0,2,4,.... Commented Feb 18, 2019 at 16:06

1 Answer 1

2

If you declare the array using bash ANSI-C Quoting

ary=($'AAA\naaa' $'BBB\nbbb' $'CCC\nccc')

Then you get what you are after.

Inspecting the contents of the array

$ declare -p ary
declare -a ary='([0]="AAA
aaa" [1]="BBB
bbb" [2]="CCC
ccc")'

Or inspect it with printf:

$ printf '>%s<\n' "${ary[@]}"
>AAA
aaa<
>BBB
bbb<
>CCC
ccc<

You can't write

 var[0]=("AAA
         aaa")

because, with the parentheses, you are attempting to store an array in an array element, and bash does not allow arrays-of-arrays.

You could write

var=(
"AAA
aaa"
"BBB
bbb"
"CCC
ccc"
)

If you have an array of words like var=(AAA aaa BBB bbb CCC ccc) then you could group elements together like this:

ary=()
for (( i=0; i < ${#var[@]}; i+=2 )); do
    ary+=( "${var[i]}"$'\n'"${var[i+1]}" )
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.