值以带模式的变量名进行数组

时间:2019-05-02 16:50:55

标签: bash

我有数量未知的变量名称,其模式为rundate *。例如,rundate=180618 && rundate2=180820。我从here知道可以将多个变量名发送到第三个变量:alld=(`echo "${!rundate*}"`),并且在尝试解决我的问题时,我弄清楚了如何将多个变量索引发送到第三个变量:{{1 }}。但是,如何向我的第三个变量alld_indices=(`echo "${!alld[@]}"`)发送多个值,以使alld_values给出echo ${alld_values[@]}。我从here知道如何获得第一个值:180618 180820。我怀疑,我已经在搜索中看到了答案,但没有意识到。如果是这样,很高兴删除我的问题。谢谢!

2 个答案:

答案 0 :(得分:2)

#!/usr/bin/env bash

# set up some test data
rundate="180618"
rundate1="180820"
rundate2="Values With Spaces Work Too"

# If we know all values are numeric, we can use a regular indexed array
# otherwise, the below would need to be ''declare -A alld=( )''
alld=( )                       # initialize an array
for v in "${!rundate@}"; do    # using @ instead of * avoids IFS-related bugs
  alld[${v#rundate}]=${!v}     # populate the array, using varname w/o prefix as key
done

# print our results
printf 'Full array definition:\n   '
declare -p alld                 # emits code that, if run, will redefine the array
echo; echo "Indexes only:"
printf ' - %s\n' "${!alld[@]}"  # "${!varname[@]}" expands to the list of keys
echo; echo "Values only:"
printf ' - %s\n' "${alld[@]}"   # "${varname[@]}" expands to the list of values

...正确发出作为输出:

Full array definition:
   declare -a alld=([0]="180618" [1]="180820" [2]="Values With Spaces Work Too")

Indexes only:
 - 0
 - 1
 - 2

Values only:
 - 180618
 - 180820
 - Values With Spaces Work Too

...如您所见,运行在https://ideone.com/yjSD1J

答案 1 :(得分:1)

循环执行

eval

$: for v in ${!rundate*}
>  do eval "alld_values+=( \$$v )"
>  done
$: echo "${alld_values[@]}"
180618 180820

$: eval "alld_values=( $( sed 's/ / $/g' <<< " ${!rundate*}" ) )"

$: echo "alld_values=( $( sed 's/ / $/g' <<< " ${!rundate*}" ) )" > tmp && . tmp