我在Bash中有一个字符串:
string="My string"
如何测试它是否包含另一个字符串?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
哪里是我不认识的接线员。我使用echo和grep吗?
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
这看起来有点笨拙。
我在Bash中有一个字符串:
string="My string"
如何测试它是否包含另一个字符串?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
哪里是我不认识的接线员。我使用echo和grep吗?
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
这看起来有点笨拙。
当前回答
您应该记住,shell脚本不是一种语言,而是一组命令。你本能地认为这种“语言”要求你在if后面加一个[或一个[[。这两个命令都只是返回一个表示成功或失败的退出状态的命令(就像其他所有命令一样)。出于这个原因,我会使用grep,而不是[命令。
只要做到:
if grep -q foo <<<"$string"; then
echo "It's there"
fi
既然您正在考虑如果测试它后面的命令的退出状态(用分号完成),为什么不重新考虑您正在测试的字符串的源代码?
## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then
#...
## Simply do this
if file -b "$1" | grep -q "tar archive"; then
#...
-q选项使grep不输出任何内容,因为我们只需要返回代码使shell展开下一个单词,并将其用作命令的输入,这是<<here文档的一行版本(我不确定这是标准还是巴什主义)。
其他回答
grep-q对于这个目的很有用。
同样使用awk:
string="unix-bash 2389"
character="@"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'
输出:
未找到
string="unix-bash 2389"
character="-"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'
输出:
建立
原始来源:http://unstableme.blogspot.com/2008/06/bash-search-letter-in-string-awk.html
您可以使用逻辑&&以更紧凑
#!/bin/bash
# NO MATCH EXAMPLE
string="test"
[[ "$string" == *"foo"* ]] && {
echo "YES"
}
# MATCH EXAMPLE
string="tefoost"
[[ "$string" == *"foo"* ]] && {
echo "YES"
}
我发现我经常需要这个功能,所以我在.bashrc中使用了一个自制的shell函数,这样我就可以随时重用它,并使用一个容易记住的名字:
function stringinstring()
{
case "$2" in
*"$1"*)
return 0
;;
esac
return 1
}
要测试$string1(例如,abc)是否包含在$string2(例如,123abcABC)中,我只需要运行striginstring“$string1”“$string2”并检查返回值,例如
stringinstring "$str1" "$str2" && echo YES || echo NO
msg="message"
function check {
echo $msg | egrep [abc] 1> /dev/null
if [ $? -ne 1 ];
then
echo "found"
else
echo "not found"
fi
}
check
这将发现a、b或c的任何出现
我使用这个函数(一个不包括但很明显的依赖项)。它通过了以下测试。如果函数返回值>0,则找到字符串。你也可以很容易地返回1或0。
function str_instr {
# Return position of ```str``` within ```string```.
# >>> str_instr "str" "string"
# str: String to search for.
# string: String to search.
typeset str string x
# Behavior here is not the same in bash vs ksh unless we escape special characters.
str="$(str_escape_special_characters "${1}")"
string="${2}"
x="${string%%$str*}"
if [[ "${x}" != "${string}" ]]; then
echo "${#x} + 1" | bc -l
else
echo 0
fi
}
function test_str_instr {
str_instr "(" "'foo@host (dev,web)'" | assert_eq 11
str_instr ")" "'foo@host (dev,web)'" | assert_eq 19
str_instr "[" "'foo@host [dev,web]'" | assert_eq 11
str_instr "]" "'foo@host [dev,web]'" | assert_eq 19
str_instr "a" "abc" | assert_eq 1
str_instr "z" "abc" | assert_eq 0
str_instr "Eggs" "Green Eggs And Ham" | assert_eq 7
str_instr "a" "" | assert_eq 0
str_instr "" "" | assert_eq 0
str_instr " " "Green Eggs" | assert_eq 6
str_instr " " " Green " | assert_eq 1
}