我在 bash 中有一个包含以下条目的数组
arr=(WEDNESDAY TUESDAY SATURDAY)
现在我必须返回前一天(根据周并且应该存在于数组中)作为输入。
input ==> output
SATURDAY ==> WEDNESDAY
TUESDAY ==> SATURDAY
WEDNESDAY ==> TUESDAY
SUNDAY ==> Null
我会创建一个关联数组来保存映射:(需要 bash 4)
arr=(WEDNESDAY TUESDAY SATURDAY)
declare -A map
for ((i=${#arr[@]}-1; i>=0; i--)); do
map[${arr[i-1]}]=${arr[i]}
done
这利用了从数组末尾读取的负数组索引。然后:
for input in "${arr[@]}" SUNDAY; do
printf "%s => %s\n" "$input" "${map[$input]:-Null}"
done
WEDNESDAY => TUESDAY
TUESDAY => SATURDAY
SATURDAY => WEDNESDAY
SUNDAY => Null
使用模运算符的解决方案%
:
#! /bin/bash
previous=(WEDNESDAY TUESDAY SATURDAY)
for input in WEDNESDAY TUESDAY SATURDAY SUNDAY ; do
for (( i=0; i<${#previous[@]}; i++ )) ; do
[[ $input == ${previous[i]} ]] && break
done
if (( i < ${#previous[@]} )) ; then
result=${previous[(i+1)%${#previous[@]}]}
else
result=Null
fi
echo $input $result
done
或者,在支持关联数组的最新版本的 bash 中:
#! /bin/bash
previous_arr=(WEDNESDAY TUESDAY SATURDAY)
declare -A previous
for ((i=0; i<${#previous_arr[@]}; i++)) ; do
p=${previous_arr[(i+1)%${#previous_arr[@]}]}
previous[${previous_arr[i]}]=$p
done
for input in WEDNESDAY TUESDAY SATURDAY SUNDAY ; do
echo $input ${previous[$input]}
done
这可以使它:
for ((i = 0; i < ${#d[@]}; i++))
do
[[ $((${#d[@]} - 1)) -eq $i ]] && next_index=0 || next_index=$((i+1))
[ "$input" == "${d[$i]}" ] && echo "${d[$next_index]}"
done
它需要将输入值存储在$input
. 然后它遍历数组并检查是否$input
匹配记录。如果是,则打印数组中的下一条记录 ( ${d[$next_index]}
)。如果它是最后一个,它会打印第一个。
要获取$next_index
值,我们使用这是三元运算符:
[[ $((${#d[@]} - 1)) -eq $i ]] && next_index=0 || next_index=$((i+1))
意思是:
if [[ $((${#d[@]} - 1)) -eq $i ]]; then
next_index=0
else
next_index=$((i+1))
fi
即$next_index
存储下一项的索引。如果它是最后一个,则为 0(第一项的索引)。
$ d=(TUESDAY SATURDAY WEDNESDAY)
$ input=SATURDAY
$ for ((i = 0; i < ${#d[@]}; i++)); do [[ $((${#d[@]} - 1)) -eq $i ]] && next_index=0 || next_index=$((i+1)); [ "$input" == "${d[$i]}" ] && echo "${d[$next_index]}"; done
WEDNESDAY
$ input=TUESDAY
$ for ((i = 0; i < ${#d[@]}; i++)); do [[ $((${#d[@]} - 1)) -eq $i ]] && next_index=0 || next_index=$((i+1)); [ "$input" == "${d[$i]}" ] && echo "${d[$next_index]}"; done
SATURDAY
$ input=WEDNESDAY
$ for ((i = 0; i < ${#d[@]}; i++)); do [[ $((${#d[@]} - 1)) -eq $i ]] && next_index=0 || next_index=$((i+1)); [ "$input" == "${d[$i]}" ] && echo "${d[$next_index]}"; done
TUESDAY
$ input=SUNDAY
$ for ((i = 0; i < ${#d[@]}; i++)); do [[ $((${#d[@]} - 1)) -eq $i ]] && next_index=0 || next_index=$((i+1)); [ "$input" == "${d[$i]}" ] && echo "${d[$next_index]}"; done
$