将变量的子字符串与unix中的另一个字符串进行比较 [英] compare a substring of variable with another string in unix

查看:108
本文介绍了将变量的子字符串与unix中的另一个字符串进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Unix的初学者。如果这个问题听起来太蹩脚,我很抱歉。



我会将一个参数传递给一个变量 fullstring = $ 1 。这个变量的输入可能类似于这些选项,例如tester.txt或tester.sh或testapiece.zip或testing.bad或 *。* 基本上它是就像包含文件名通配符模式的字符串以及文件类型一样。



这里我需要从参数中传递的字符串中删除文件类型,即基本上我需要将字符串从。中剪切掉。直到最后,我需要将它与IF子句中的多个字符串进行比较。



代码结构大纲将类似于以下结构:

 如果变量的子字符串(只是变量中的文件类型)不等于任何4个预定义文件类型字符串(txt,zip,csv, *)
THEN
ECHO文件不在所需文件类型中
EXIT
ELSE
ECHO文件处于所需文件类型
FI

如果有人能够帮助我处理IF条件中的条件,那将会很有帮助。注意:我们可以传递字面值 * 作为文件类型,它应该直接与

解决方案

扩展hek2mgl的ksh解决方案, 4个不同的扩展:

  str =a.txt
if [[$ {str ## *。 }= @(txt | zip | csv | \ *)]];那么
做这个
else
做那个
fi



< '@'是一个多模式匹配结构。在这种情况下,它需要字符串'txt','zip','csv'或星号作为字符'*'的精确匹配。



星号有如果是[[$ {str ## *。},那么它将被作为通配符处理,例如:

  = @(* txt *)]] ... ... 

会匹配' txt ','abc txt ',' txt def','abc txt def'


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 *

解决方案

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'

这篇关于将变量的子字符串与unix中的另一个字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆