在 Bash 中,如何查看字符串是否不在数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15901239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Bash how do you see if a string is not in an array?
提问by blamonet
I'm trying to do this without adding additional code, such as another for loop. I can create the positive logic of comparing a string to an array. Although I want the negative logic and only print values not in the array, essentially this is to filter out system accounts.
我正在尝试在不添加其他代码(例如另一个 for 循环)的情况下执行此操作。我可以创建将字符串与数组进行比较的正逻辑。虽然我想要负逻辑并且只打印不在数组中的值,但本质上这是为了过滤掉系统帐户。
My directory has files in it like this:
我的目录中有这样的文件:
admin.user.xml
news-lo.user.xml
system.user.xml
campus-lo.user.xml
welcome-lo.user.xml
This is the code I used to do a positive match if that file is in the directory:
如果该文件在目录中,这是我用来进行正匹配的代码:
#!/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
Any help in the right direction would be appreciated, thanks.
任何在正确方向上的帮助将不胜感激,谢谢。
回答by chepner
You can negate the result of the positive match:
您可以否定正匹配的结果:
if ! [[ ${accounts[*]} =~ "$account" ]]
or
或者
if [[ ! ${accounts[*]} =~ "$account" ]]
However, notice that if $account
equals "user", you'll get a match, since it matches a substring of "power_user". It's best to iterate explicitly:
但是,请注意,如果$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