怎么前一天从bash中的数组

时间:2013-08-07 09:11:26

标签: bash shell

我在bash中有一个包含以下条目的数组

arr=(WEDNESDAY TUESDAY SATURDAY)

现在我必须返回前一天(根据星期并且应该出现在数组中)进行输入。

input     ==> output
SATURDAY  ==> WEDNESDAY
TUESDAY   ==> SATURDAY
WEDNESDAY ==> TUESDAY
SUNDAY    ==> Null

3 个答案:

答案 0 :(得分:2)

我会创建一个关联数组来保存映射:(需要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

答案 1 :(得分:0)

这可以做到:

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
$ 

答案 2 :(得分:0)

使用模运算符%的解决方案:

#! /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