csh/tcsh 如何查找特定字符串是否在 variable/filename 中?

csh/tcsh How to find if a particular string is in a variable/filename?

我想检查一个特定的字符串是否在文件名中(这是一个变量)。 [在 csh/tcsh]

#!/bin/tcsh
set file = 'KZ.KKAR..BHZ.2008-01-18T19-16-51.SAC'
set string = 'BHZ'
echo $file
if [[$file == *$string*]];then
    echo 'string contains in this'
else 
    echo "NOOOOOOOOO"
endif

像这样。 要么 如果可能的话,在一行代码中

您可以使用 =~ 来匹配 glob 模式:

if ( $file =~ *$string* ) then

注意 [[..]]; then 是无效的 (t)csh 语法;这仅适用于 Bourne shell.

这在 man tcsh 中有记录:

The '==' '!=' '=~' and '!~' operators compare their arguments as strings; all others operate on numbers. The operators '=~' and '!~' are like '!=' and '==' except that the right hand side is a glob-pattern (see Filename substitution) against which the left hand operand is matched. This reduces the need for use of the switch builtin command in shell scripts when all that is really needed is pattern matching.

如文档所述,switch 也可以使用 glob 模式,类似于 谍影重重 shell.