问题 在Bash中,您如何查看字符串是否不在数组中?


我试图这样做而不添加额外的代码,例如另一个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

在正确的方向上的任何帮助将不胜感激,谢谢。


11704
2018-04-09 11:57


起源

你可能意味着 for file in user/*; do (注意 ;) - devnull
谢谢,有人对我的问题进行了编辑,并意外删除了回车。 - blamonet


答案:


你可以否定积极匹配的结果:

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

14
2018-04-09 12:02



我编辑了原来的问题,谢谢你的澄清。 - blamonet
对不起,我没有仔细阅读你的问题。我编辑了这个以便现在回答你的问题。 - chepner
很好的建议,谢谢。 - blamonet
有一个 then 失踪了 if 表达: if [[ $acc = "$account" ]]; then - Stanislav