gpt4 book ai didi

arrays - 在不知道位置的情况下从数组中删除(不仅仅是取消设置)多个字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:52 26 4
gpt4 key购买 nike

假设我有数组

a1=(cats,cats.in,catses,dogs,dogs.in,dogses)
a2=(cats.in,dogs.in)

除了完全匹配的字符串(包括“.in”)之外,我想在删除“.in”之后从 a1 中删除与 a2 中的字符串匹配的所有内容。

因此,我想从 a1 中删除 cats、cats.in、dogs、dogs.in,但不删除 catses 或 dogses。

我想我必须分两步完成。我找到了如何删除“.in”:

for elem in "${a2[@]}" ; do 
var="${elem}"
len="${#var}"
pref=${var:0:len-3}
done

^ 这给了我“猫”和“狗”

我需要向循环删除 a1 中的每个元素添加什么命令?

最佳答案

在我看来,解决这个问题的最简单方法是使用嵌套的 for 循环:

#!/usr/bin/env bash

a1=(cats cats.in catses dogs dogs.in dogses)
a2=(cats.in dogs.in)

for x in "${!a1[@]}"; do # step through a1 by index
for y in "${a2[@]}"; do # step through a2 by content
if [[ "${a1[x]}" = "$y" || "${a1[x]}" = "${y%.in}" ]]; then
unset a1[x]
fi
done
done

declare -p a1

但根据您的实际数据,以下可能更好,使用两个单独的 for 循环而不是嵌套。

#!/usr/bin/env bash

a1=(cats cats.in catses dogs dogs.in dogses)
a2=(cats.in dogs.in)

# Flip "a2" array to "b", stripping ".in" as we go...
declare -A b=()
for x in "${!a2[@]}"; do
b[${a2[x]%.in}]="$x"
done

# Check for the existence of the stripped version of the array content
# as an index of the associative array we created above.
for x in "${!a1[@]}"; do
[[ -n "${b[${a1[x]%.in}]}" ]] && unset a1[$x] a1[${x%.in}]
done

declare -p a1

这里的优点是,您不必为 a1 中的每个项目循环遍历所有 a2,您只需在每个数组上循环一次。缺点可能取决于您的数据。例如,如果 a2 的内容非常大,您可能会达到内存限制。当然,我无法从您问题中包含的内容中得知这一点;此解决方案适用于您提供的数据。

注意:此解决方案还依赖于 关联数组,这是 bash 版本 4 中引入的一项功能。如果您运行的是旧版本的 bash,现在可能是时候升级。 :)

关于arrays - 在不知道位置的情况下从数组中删除(不仅仅是取消设置)多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34984661/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com