Bash shell中测试,如果在一个字符串中的所有字符都在另一个字符串 [英] Bash shell test if all characters in one string are in another string
问题描述
我有两个字符串,我想比较平等的字符,字符串必须包含确切的字符,但是可以mychars有多余的字符。
I have two strings which I want to compare for equal chars, the strings must contain the exact chars but mychars can have extra chars.
mychars="abcdefg"
testone="abcdefgh" # false h is not in mychars
testtwo="abcddabc" # true all char in testtwo are in mychars
function test() {
if each char in $1 is in $2 # PSEUDO CODE
then
return 1
else
return 0
fi
}
if test $testone $mychars; then
echo "All in the string" ;
else ; echo "Not all in the string" ; fi
# should echo "Not all in the string" because the h is not in the string mychars
if test $testtwo $mychars; then
echo "All in the string" ;
else ; echo "Not all in the string" ; fi
# should echo 'All in the string'
什么是做到这一点的最好方法是什么?我的猜测是遍历第一个参数的所有字符。
What is the best way to do this? My guess is to loop over all the chars in the first parameter.
推荐答案
您可以使用 TR
从 mychars $ C替换任何字符$ C>用一个符号,那么你就可以测试,如果生成的字符串是从符号有什么不同,PE:
You can use tr
to replace any char from mychars
with a symbol, then you can test if the resulting string is any different from the symbol, p.e.,:
tr -s "[$mychars]" "." <<< "ggaaabbbcdefg"
输出:
.
不过:</ P>
But:
tr -s "[$mychars]" "." <<< "xxxggaaabbbcdefgxxx"
打印:
xxx.xxx
所以,你的函数可能是这样的:
So, your function could be like the following:
function test() {
local dictionary="$1"
local res=$(tr -s "[$dictionary]" "." <<< "$2")
if [ "$res" == "." ]; then
return 1
else
return 0
fi
}
更新::由 @ mklement0 建议,全功能可以缩短(和由以下逻辑固定):
Update: As suggested by @mklement0, the whole function could be shortened (and the logic fixed) by the following:
function test() {
local dictionary="$1"
[[ '.' == $(tr -s "[$dictionary]" "." <<< "$2") ]]
}
这篇关于Bash shell中测试,如果在一个字符串中的所有字符都在另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!