0

I have a way to siplt the string into a array with shell ,but the array seems no value

>>> a='11 12 13 14'
>>> echo $a | awk '{split($0,arr," ")'
1 11
2 12
3 13
4 14
>>> echo ${arr[0]}

>>>

the expected result should be
>>> echo ${arr[0]}
11

how could I store the value into the array after the string splitted

2
  • 1
    Are you using shell or bash ? Because shell sh does not support array. Commented Jul 18, 2022 at 3:45
  • Care, @Liso is correct: ${arr[@]} is not a valid syntax under POSIX shell! Commented Jul 18, 2022 at 7:14

3 Answers 3

1

If the values are "nice" - no filename expansion trigger characters and elements are nicely separated by spaces - just read the array.

arr=($a)

A way better and safer version, is to use readarray or mapfile.

readarray -d ' ' -t arr < <(printf "%s" "$a")
readarray -t arr <<<"${a// /$'\n'}"
Sign up to request clarification or add additional context in comments.

Comments

1
#!/bin/bash

a='11 12 13 14 15'

IFS=' ' read -r -a arr <<<"$a"
declare -p arr

arr2=($a)
declare -p arr2

Output

declare -a arr2=([0]="11" [1]="12" [2]="13" [3]="14" [4]="15")
declare -a arr2=([0]="11" [1]="12" [2]="13" [3]="14" [4]="15")

Comments

0

You need to return the output of awk to a shell variable.

$> a='11 12 13 14'
$> arr=($(echo $a | awk '{n=split($0,arr," ");for (i=1;i<=n;i++) { print arr[i] } }'))
$> echo ${arr[0]}
11

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.