【问题标题】:In Bash how do you see if a string is not in an array?在 Bash 中,如何查看字符串是否不在数组中?
【发布时间】:2013-03-31 20:12:07
【问题描述】:

我正在尝试在不添加其他代码(例如另一个 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

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

【问题讨论】:

  • 你的意思可能是for file in user/*; do(注意;
  • 谢谢,有人对我的问题进行了编辑,不小心删除了回车。

标签: bash shell scripting


【解决方案1】:

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

if echo "${accounts[*]}"|egrep -q "\b$account}\b"; then ...

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • 对不起,我没有仔细阅读您的问题。我已经编辑了这个以实际回答您的问题。
    • if 表达式中缺少thenif [[ $acc = "$account" ]]; then
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多