Linux Shell脚本-带通配符的字符串比较 [英] Linux Shell Script - String Comparison with wildcards
问题描述
我正在尝试查看一个字符串是否是Shell脚本(#!bin/sh)中另一个字符串的一部分.
I am trying to see if a string is part of another string in shell script (#!bin/sh).
我现在拥有的代码是:
#!/bin/sh
#Test scriptje to test string comparison!
testFoo () {
t1=$1
t2=$2
echo "t1: $t1 t2: $t2"
if [ $t1 == "*$t2*" ]; then
echo "$t1 and $t2 are equal"
fi
}
testFoo "bla1" "bla"
我要寻找的结果是,我想知道"bla1"中何时存在"bla".
The result I'm looking for, is that I want to know when "bla" exists in "bla1".
谢谢和亲切的问候,
UPDATE: I've tried both the "contains" function as described here: How do you tell if a string contains another string in Unix shell scripting?
但是,它们似乎与普通的shell脚本(bin/sh)不兼容...
However, they seem to be non compatible with normal shell script (bin/sh)...
帮助?
推荐答案
在bash中,您可以编写(请注意,星号在引号的外部之外)
In bash you can write (note the asterisks are outside the quotes)
if [[ $t1 == *"$t2"* ]]; then
echo "$t1 and $t2 are equal"
fi
对于/bin/sh,=
运算符仅用于相等性,不适用于模式匹配.您可以使用case
For /bin/sh, the =
operator is only for equality not for pattern matching. You can use case
though
case "$t1" in
*"$t2"*) echo t1 contains t2 ;;
*) echo t1 does not contain t2 ;;
esac
如果您专门针对linux,则假定存在/bin/bash.
If you're specifically targetting linux, I would assume the presence of /bin/bash.
这篇关于Linux Shell脚本-带通配符的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!