如何在fish shell中测试一个字符串是否包含另一个字符串?

18

在fish shell中如何测试子字符串的存在?例如,在switch表达式中:

 set myvar "a long test string"
 switch $myvar
 case magical-operator-here "test string" 
     echo 'yep!'
 case '*'
     echo 'nope!'
 end
1个回答

34

*是通配符,因此

set myvar "a long test string"
switch $myvar
case "*test string" 
    echo 'yep!'
case '*'
    echo 'nope!'
end

如果您想测试它是否以该字符串结尾。 如果它还可以出现在中间,请在末尾添加另一个*

此外,自2.3.0以来,fish已具有一个string内置程序,其中包含一个match子命令,因此您也可以使用string match -q -- "*test string" $myvar。 它还支持带有“-r”选项的pcre样式正则表达式。


3
我非常欣赏你在StackOverflow关于fish shell的回答。 - ipatch
谢谢!“字符串匹配”命令就是我要找的。 - Wray Zheng
如果它也可以出现在中间的某个地方,请在末尾添加另一个*。像这样。set myvar "a long test string" switch $myvar case "*test string*" echo 'yep!' case '*' echo 'nope!' end - WeiHua Liu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接