bash script to check file name begins with expected string

↘锁芯ラ 提交于 2019-12-04 07:52:53

In bash, you can get the first 7 characters of a shell variable with:

${sourceFile:0:7}

and the last four with:

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

Armed with that knowledge, simply use those expressions where you would normally use the variable itself, something like the following script:

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

You can see it in action with the following transcript:

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

=~ operator requires regexp, not wildcard. == accepts wildcards, but they should not be quoted:

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

You may use a regexp too of course, but it would be a bit overkill:

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

Please note that regexp is open by default (a == .*a.*) while glob is closed (a != *a*).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!