【问题标题】:How to check in shell script if string variable contains a wildcard?如果字符串变量包含通配符,如何签入shell脚本?
【发布时间】:2013-04-23 15:38:41
【问题描述】:

我正在尝试检查字符串是否包含任何通配符。 这是我失败的尝试:

#!/bin/bash
WILDCARDS='* . ? !  ] [' 
a="foo*bar"
for x in $REJECTED_WILDCARDS
do 
    if [[ "$a" == *"$x"* ]]
    then 
            echo "It's there!";
    fi 
done

有什么建议吗?

【问题讨论】:

  • 为什么.会包含在列表中?

标签: bash shell wildcard


【解决方案1】:

略短且没有循环:

if [ "$a" != "${a//[\[\]|.? +*]/}"  ] ; then
  echo "wildcard found"
fi

参数替换删除所有通配符。 字符串不再相等。

【讨论】:

  • 我更喜欢这种方法。
【解决方案2】:

将通配符设置为 bash 数组,就像这样

wildcards=( '*' '.' '?' '|' ']' '[' )

然后

a="foo*bar"
for wildcard in "${wildcards[@]}";
do
  if [[ $a == *"${wildcard}"* ]];
  then
    echo 'yes';
  fi;
 done

【讨论】:

  • 太好了,这就是我一直在寻找的。出于好奇,如何在此列表中添加单引号?
  • @user52028778,用双引号来引用它,像这样:wildcards=( '*' '.' '?' '|' ']' '[', "'" )
猜你喜欢
  • 2021-05-25
  • 2022-11-27
  • 2012-11-02
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多