bash 检查文件名的bash脚本以预期的字符串开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25416991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash script to check file name begins with expected string
提问by chop
Running on OS X with a bash script:
使用 bash 脚本在 OS X 上运行:
sourceFile=`basename `
shopt -s nocasematch
if [[ "$sourceFile" =~ "adUsers.txt" ]]; then echo success ; else echo fail ; fi
The above works, but what if the user sources a file called adUsers_new.txt
?
上面的方法有效,但是如果用户获取一个名为adUsers_new.txt
?
I tried:
我试过:
if [[ "$sourceFile" =~ "adUsers*.txt" ]]; then echo success ; else echo fail ; fi
But the wildcard doesn't work in this case.
I'm writing this script to allow for the user to have different iterations of the source file name, which must begin with aduser
and have the .txt
file extension.
但是在这种情况下通配符不起作用。我正在编写此脚本以允许用户对源文件名进行不同的迭代,源文件名必须以文件扩展名开头aduser
并具有.txt
文件扩展名。
回答by paxdiablo
In bash
, you can get the first 7 characters of a shell variable with:
在 中bash
,您可以使用以下命令获取 shell 变量的前 7 个字符:
${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=
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
回答by Dmitry Alexandrov
=~
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*
).
请注意,regexp 默认是打开的(a
== .*a.*
),而 glob 是关闭的(a
!= *a*
)。