簡體   English   中英

比較變量的子字符串與UNIX中的另一個字符串

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

我是Unix的初學者。 如果問題聽起來太la腳,我表示歉意。

我將參數傳遞給變量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子句中進行比較的條件會有所幫助。 提前致謝。

注意:我們可以通過文字*作為文件類型,應該從字面上相比*

它是這樣的:

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

擴展了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”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM