我是Unix的初学者。如果这个问题听起来太蹩脚,我道歉。
我将一个参数传递给变量fullstring=$1
。此变量的输入可能与这些选项类似,例如tester.txt或tester.sh或testapiece.zip或testing.bad或*.*
基本上它类似于包含文件名通配符模式的字符串以及文件类型。
这里我需要从参数中传递的字符串中剪切文件类型,即基本上我需要从“。”中剪切字符串。直到最后,我需要将它与IF子句中的多个字符串进行比较。
代码结构大纲将类似于以下结构:
IF substring of variable(just the filetype in the variable) is not equals to any of the set of 4 predefined file type strings (txt,zip,csv,*)
THEN
ECHO "file is not in the required file type"
EXIT
ELSE
ECHO "file is in required file type"
FI
如果有人可以帮助我在IF条款中进行比较,那将会很有帮助。提前谢谢。
注意:我们可以将文字*
作为文件类型传递,应该按字面意思与*
进行比较
答案 0 :(得分:1)
它的工作原理如下:
str="a.txt"
if [ "${str##*.}" = "txt" ] ; then
do this
else
do that
fi
${str##*.}
是所谓的参数扩展。在此处查找有关此内容的更多信息:http://www.informit.com/articles/article.aspx?p=99035&seqNum=3
答案 1 :(得分:1)
扩展hek2mgl的ksh解决方案,包括测试4种不同的扩展程序:
str="a.txt"
if [[ "${str##*.}" = @(txt|zip|csv|\*) ]]; then
do this
else
do that
fi
' @'是一种多模式匹配结构。在这种情况下,它要求完全匹配字符串' txt',' zip'' csv'或星号作为字符' *'。
必须转义星号,否则将其视为通配符,例如:
if [[ "${str##*.}" = @(*txt*) ]] ...
将匹配' txt ',' abc txt ',' txt def',' abc txt def'