[英]Search array return index in bash
只是pesuocode,但这基本上是我想做的。
Array=("1" "Linux" "Test system"
"2" "Windows" "Workstation"
"3" "Windows" "Workstation")
echo "number " ${array[search "$1"]} "is a" ${array[search "$1" +1]} ${array[search "$1" +2])}
这可能与bash有关吗? 我只能找到有关搜索和替换的信息。 我没有看到任何可以返回和索引的东西。
这样的东西应该工作:
search() {
local i=1;
for str in "${array[@]}"; do
if [ "$str" = "$1" ]; then
echo $i
return
else
((i++))
fi
done
echo "-1"
}
虽然循环遍历数组以找到索引当然是可能的,但这种具有关联数组的替代解决方案更实用:
array=([1,os]="Linux" [1,type]="Test System"
[2,os]="Windows" [2,type]="Work Station"
[3,os]="Windows" [3,type]="Work Station")
echo "number $1 is a ${array[$1,os]} ${array[$1,type]}"
您可以从此链接修改此示例以返回索引而不会有太多麻烦:
# Check if a value exists in an array
# @param $1 mixed Needle
# @param $2 array Haystack
# @return Success (0) if value exists, Failure (1) otherwise
# Usage: in_array "$needle" "${haystack[@]}"
# See: http://fvue.nl/wiki/Bash:_Check_if_array_element_exists
in_array() {
local hay needle=$1
shift
for hay; do
[[ $hay == $needle ]] && return 0
done
return 1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.