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
CodePudding user response:
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'}"
CodePudding user response:
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
CodePudding user response:
#!/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")