Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于检查文件名的bash脚本以预期字符串开头_Bash_If Statement_Pattern Matching_String Matching - Fatal编程技术网

用于检查文件名的bash脚本以预期字符串开头

用于检查文件名的bash脚本以预期字符串开头,bash,if-statement,pattern-matching,string-matching,Bash,If Statement,Pattern Matching,String Matching,使用bash脚本在OS X上运行: sourceFile=`basename $1` shopt -s nocasematch if [[ "$sourceFile" =~ "adUsers.txt" ]]; then echo success ; else echo fail ; fi 上述方法可行,但如果用户源文件名为adUsers\u new.txt,该怎么办 我试过: if [[ "$sourceFile" =~ "adUsers*.txt" ]]; then echo success

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

sourceFile=`basename $1`
shopt -s nocasematch
if [[ "$sourceFile" =~ "adUsers.txt" ]]; then echo success ; else echo fail ; fi
上述方法可行,但如果用户源文件名为
adUsers\u new.txt
,该怎么办

我试过:

if [[ "$sourceFile" =~ "adUsers*.txt" ]]; then echo success ; else echo fail ; fi
但通配符在这种情况下不起作用。
我编写此脚本是为了允许用户对源文件名进行不同的迭代,源文件名必须以
aduser
开头,并具有
.txt
文件扩展名。

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

=~
运算符需要regexp,而不是通配符
=
接受通配符,但不应引用它们:

if [[ "$sourceFile" == adUsers*.txt ]]; then echo success; else echo fail; fi
当然,您也可以使用regexp,但这有点过分:

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

请注意,默认情况下,regexp是打开的(
a
=
*a.*
),而glob是关闭的(
a
!=
*a*
)。

我相信您不需要引用
=~
操作符的RHS。这无疑是有效的。但是为什么呢?为什么不直接使用通配符匹配呢?