从bash数组中删除项目和索引

时间:2015-04-18 09:33:18

标签: arrays bash

我正在尝试删除另一个数组中也存在的数组项。例如:

a=(a b c d)
b=(a d)

for ((i=0; i<${#a[@]}; i++)); do
    for j in "${b[@]}" ; do
        [[ $j == ${a[$i]} ]] && unset a[$i]
    done
done

for ((i=0; i<${#a[@]}; i++ )); do
    echo "$i: ${a[$i]}"
done

输出结果为:

0: 
1: b
2: c

如何摆脱虚拟零指数?预期的产出将是:

0: b
1: c

2 个答案:

答案 0 :(得分:2)

你试过这个吗?

a=(a b c d)
b=(a d)

for i in "${b[@]}"; do
    a=(${a[@]/$i})
done

for ((i=0; i<${#a[@]}; i++ )); do
    echo "$i: ${a[$i]}"
done

答案 1 :(得分:1)

尝试类似:

 for i in "${b[@]}"; do ##for every entry in array b
     a=(${a[@]//$i})  ## remove the entry within a that matches exactly what b has
 done