我试图在不添加额外代码(例如另一个 for 循环)的情况下执行此操作。我可以创建将字符串与数组进行比较的正逻辑。虽然我想要负逻辑,只打印不在数组中的值,但本质上这是为了过滤掉系统帐户。
我的目录中有这样的文件:
admin.user.xml
news-lo.user.xml
system.user.xml
campus-lo.user.xml
welcome-lo.user.xml
如果该文件在目录中,这是我用来进行正匹配的代码:
#!/bin/bash
accounts=(guest admin power_user developer analyst system)
for file in user/*; do
temp=${file%.user.xml}
account=${temp#user/}
if [[ ${accounts[*]} =~ "$account" ]]
then
echo "worked $account";
fi
done
在正确方向上的任何帮助将不胜感激,谢谢。
最佳答案
您可以否定正匹配的结果:
if ! [[ ${accounts[*]} =~ "$account" ]]
或
if [[ ! ${accounts[*]} =~ "$account" ]]
但是,请注意,如果 $account
等于“user”,您将得到一个匹配项,因为它与“power_user”的子字符串匹配。最好明确地迭代:
match=0
for acc in "${accounts[@]}"; do
if [[ $acc = "$account" ]]; then
match=1
break
fi
done
if [[ $match = 0 ]]; then
echo "No match found"
fi
关于bash - 在 Bash 中,如何查看字符串是否不在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15901239/