在Bash中,如何查看字符串是否不在数组中? [英] In Bash how do you see if a string is not in an array?

查看:71
本文介绍了在Bash中,如何查看字符串是否不在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试不添加其他代码(例如另一个for循环)来执行此操作.我可以创建将字符串与数组进行比较的肯定逻辑.尽管我希望使用否定逻辑,并且只在数组中不显示值,但这实际上是要过滤掉系统帐户.

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.

我的目录中包含这样的文件:

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.

推荐答案

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

You can negate the result of the positive match:

if ! [[ ${accounts[*]} =~ "$account" ]]

if [[ ! ${accounts[*]} =~ "$account" ]]

但是,请注意,如果 $ account 等于"user",则会得到一个匹配项,因为它匹配了"power_user"的子字符串.最好进行显式迭代:

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:

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中,如何查看字符串是否不在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆