简体   繁体   English

比较变量的子字符串与UNIX中的另一个字符串

[英]compare a substring of variable with another string in unix

I am a beginner in Unix. 我是Unix的初学者。 My apologies if the question sounds too lame. 如果问题听起来太la脚,我表示歉意。

I will be passing an argument to a variable fullstring=$1 . 我将参数传递给变量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. 此变量的输入可能类似于这些选项,例如tester.txt或tester.sh或testapiece.zip或testing.bad或*.*基本上,这类似于包含文件名通配符模式以及文件类型的字符串。

Here I need to cut just the file type from the string that is passed in the argument ie basically i need to cut the string from "." 在这里,我只需要从参数中传递的字符串中剪切文件类型,即基本上我需要从“。”中剪切字符串。 till the end and I need to compare it with multiple strings in the IF clause. 直到最后,我需要将其与IF子句中的多个字符串进行比较。

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. 如果有人可以帮助我在IF子句中进行比较的条件会有所帮助。 Thanks in advance. 提前致谢。

Note: we can pass literal * as the file type, it should be compared literally to the * 注意:我们可以通过文字*作为文件类型,应该从字面上相比*

It works like this: 它是这样的:

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

${str##*.} is a so called parameter expansion. ${str##*.}是所谓的参数扩展。 Find more info about that here: http://www.informit.com/articles/article.aspx?p=99035&seqNum=3 在此处找到有关此的更多信息: http : //www.informit.com/articles/article.aspx?p= 99035& seqNum=3

Expanding on hek2mgl's ksh solution to include testing for the 4 different extensions: 扩展了hek2mgl的ksh解决方案,以包括对4种不同扩展的测试:

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 '*'. 在这种情况下,它要求字符串'txt','zip','csv'或星号与字符'*'完全匹配。

The asterisk has to be escaped otherwise it's treated as a wildcard character, eg: 星号必须转义,否则将被视为通配符,例如:

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

will match ' txt ', 'abc txt ', ' txt def', 'abc txt def' 将匹配“ txt ”,“ abc txt ”,“ txt def”,“ abc txt def”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM