【问题标题】:bash script to check file name begins with expected string用于检查文件名的 bash 脚本以预期的字符串开头
【发布时间】:2014-08-21 01:30:23
【问题描述】:

使用 bash 脚本在 OS X 上运行:

sourceFile=`basename $1`
shopt -s nocasematch
if [[ "$sourceFile" =~ "adUsers.txt" ]]; then echo success ; else echo fail ; fi

上述方法可行,但如果用户获取一个名为 adUsers_new.txt 的文件怎么办?

我试过了:

if [[ "$sourceFile" =~ "adUsers*.txt" ]]; then echo success ; else echo fail ; fi

但通配符在这种情况下不起作用。 我正在编写此脚本以允许用户对源文件名进行不同的迭代,源文件名必须以 aduser 开头并具有 .txt 文件扩展名。

【问题讨论】:

  • 我相信你不需要引用=~运营商的RHS。

标签: bash if-statement pattern-matching string-matching


【解决方案1】:

bash 中,您可以获得shell 变量的前7 个字符:

${sourceFile:0:7}

最后四个是:

${sourceFile:${#sourceFile}-4}

有了这些知识,只需在通常使用变量本身的地方使用那些表达式,类似于以下脚本:

arg=$1
shopt -s nocasematch
i7f4="${arg:0:7}${arg:${#arg}-4}"
if [[ "${i7f4}" = "adusers.txt" ]] ; then
    echo Okay
else
    echo Bad
fi

您可以通过以下脚本查看它的实际效果:

pax> check.sh hello
Bad

pax> check.sh addUsers.txt
Bad

pax> check.sh adUsers.txt
Okay

pax> check.sh adUsers_new.txt
Okay

pax> check.sh aDuSeRs_stragngeCase.pdf.gx..txt
Okay

【讨论】:

  • 这无疑是有效的。但为什么?为什么不直接使用通配符匹配?
【解决方案2】:

=~ 运算符需要正则表达式,而不是通配符。 == 接受通配符,但不应引用它们:

if [[ "$sourceFile" == adUsers*.txt ]]; then echo success; else echo fail; fi

当然,你也可以使用正则表达式,但这有点矫枉过正:

if [[ "$sourceFile" =~ ^adUsers.*\.txt$ ]]; then echo success; else echo fail; fi

请注意,正则表达式默认打开 (a == .*a.*),而 glob 关闭 (a!= *a*)。

【讨论】:

    猜你喜欢
    • 2013-03-02
    • 2015-01-04
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2022-11-02
    • 2011-05-01
    相关资源
    最近更新 更多