16

我正在尝试在不添加其他代码的情况下执行此操作,例如另一个 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

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

4

2 回答 2

24

您可以否定正匹配的结果:

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
于 2013-04-09T12:02:27.987 回答
0

以下内容也适用于完全匹配

if echo "${accounts[*]}"|egrep -q "\b$account}\b"; then ...
于 2021-12-20T11:22:02.997 回答