compare a substring of variable with another string in unix

*爱你&永不变心* 提交于 2019-12-12 04:45:20

问题


I am a beginner in Unix. My apologies if the question sounds too lame.

I will be passing an argument to a variable fullstring=$1. The input for this variable might be something similar to these options, for example tester.txt or tester.sh or testapiece.zip or testing.bad or *.* Basically it is something like the string containing the filename wildcard pattern along with file type.

Here I need to cut just the file type from the string that is passed in the argument i.e. basically i need to cut the string from "." till the end and I need to compare it with multiple strings in the IF clause.

Code structure outline will be similar to the below structure:

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

It will be helpful if some one can help me with the condition to compare in IF clause. Thanks in advance.

Note: we can pass literal * as the file type, it should be compared literally to the *


回答1:


It works like this:

str="a.txt"
if [ "${str##*.}" = "txt" ] ; then
    do this
else
    do that
fi

${str##*.} is a so called parameter expansion. Find more info about that here: http://www.informit.com/articles/article.aspx?p=99035&seqNum=3




回答2:


Expanding on hek2mgl's ksh solution to include testing for the 4 different extensions:

str="a.txt"
if [[ "${str##*.}" = @(txt|zip|csv|\*) ]]; then
    do this
else
    do that
fi

The '@' is a multi-pattern matching construct. In this case it's asking for an exact match of strings 'txt', 'zip', 'csv' or the asterisk as a character '*'.

The asterisk has to be escaped otherwise it's treated as a wildcard character, eg:

if [[ "${str##*.}" = @(*txt*) ]] ...

will match 'txt', 'abctxt', 'txtdef', 'abctxtdef'



来源:https://stackoverflow.com/questions/44163452/compare-a-substring-of-variable-with-another-string-in-unix

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