这可能是bash
中无法完成的事情。我有一个if
,它在数组的元素中搜索字符串,然后返回找到的元素,这是一个网址。我进一步需要if
要做的是通过名称检查同一字符串的几个不同数组,并返回那些匹配的元素。
到目前为止,我已经构建了这个:
# Array addresses
node1=( "http://website111.com/detail.php?hostid=12345" "http://website222.com/detail.php?hostid=23456" "http://website333.com/detail.php?hostid=345678" )
node2_2=( "http://website111.com/detail.php?hostid=456789" "http://website222.com/detail.php?hostid=567890" "http://website333.com/detail.php?hostid=012345" )
node3_8=( "http://website111.com/detail.php?hostid=112233" "http://website222.com/detail.php?hostid=223344" "http://website333.com/detail.php?hostid=334455" )
node4_2=( "http://website111.com/detail.php?hostid=556677" "http://website222.com/detail.php?hostid=889900" "http://website333.com/detail.php?hostid=998877" )
node5_6=( "http://website111.com/detail.php?hostid=887766" "http://website222.com/detail.php?hostid=776655" "http://website333.com/detail.php?hostid=665544" )
# Array host names
hosts=( "node1" "node2_2" "node3_8" "node4_2" "node5_6" )
# String to find
value="website222"
# This is as far as I can get
for ((index=0; index<${#hosts[@]}; index++)); do
#This works for a single named array--> if [[ "${node2_2[$index]}" =~ (^|[^[:alpha:]])$value([^[:alpha:]]|$) ]]; then
#But here I want to use the array named saved in $hosts--> if [[ "${hosts[$index]}" =~ (^|[^[:alpha:]])$value([^[:alpha:]]|$) ]]; then
printf "%s\t%s\n" "$index" "${node2_2[$index]}"
printf "%s\t%s\n" "$index" "${hosts[$index]}"
fi
done
我认为也许“ eval”可以帮助我,但是我对语法感到茫然。
答案 0 :(得分:0)
您可以不使用eval
来执行此操作。 bash
提供了一种使用名称引用内置(typeset/local or declare -n
)引用变量/数组名称的方法(至少需要bash
的v4.3版本)。
你可以做
for array in "${hosts[@]}"; do
declare -n arr="$array"
for elem in "${arr[@]}"; do
if [[ $elem =~ (^|[^[:alpha:]])$value([^[:alpha:]]|$) ]]; then
printf '%s\n' "$elem"
fi
done
done
(可选)您还可以使用array
变量打印从中找到该数组的数组
printf 'Array Name = %s\n' "$array"