字符串包含字符bash



bash中,我试图测试一个句子是否是pangram。

read sentence
if [[ "$sentence" == [Aa] && [Bb] && [Cc] && [Dd] && [Ee] && [Ff] && [Gg] && [Hh] && [Ii] && [Jj] && [Kk] && [Ll] && [Mm] && [Nn] && [Oo] && [Pp] && [Qq] && [Rr] && [Ss] && [Tt] && [Uu] && [Vv] && [Ww] && [Xx] && [Yy] && [Zz] ]]; then
echo "pangram"
else
echo "not pangram"
fi

这是我到目前为止的代码,我得到的只是"not pangram"的输出。有人知道我的代码出了什么问题吗?

我试图操纵我之前一个问题中的代码。

测试pangram的一种更好且纯粹的Bash方法是(作为函数编写):

is_pangram() {
    local l=${1,,} i
    for i in {a..z}; do
        [[ $l = *$i* ]] || return 1
    done
    return 0
}

此函数首先将其参数转换为小写:${1,,}的扩展名是转换为小写的$1的扩展名;我们将该值存储在局部变量CCD_ 4中。然后,我们用for i in {a..z}循环遍历(小写字母),并使用glob(而不是正则表达式,在这种情况下,它会被过度使用)来检查$l是否包含该字母。

那就试试吧:

$ if is_pangram "Cwm fjord bank glyphs vext quiz"; then echo "it's a pangram"; else echo "not a pangram"; fi
it's a pangram
$ if is_pangram "the horse jumps over the fence"; then echo "it's a pangram"; else echo "not a pangram"; fi
not a pangram

您的语法几乎是正确的,但需要更多的重复。你需要这样的东西:

[[ "$sentence" =~ [Aa] && "$sentence" =~ [Bb] && "$sentence" =~ [Cc] && ... ]]

毫无疑问,还有更简洁的方法可以做到这一点。

您可以使用常见的*nix命令吗?还是仅限于纯bash操作和内置?

如果允许排序,那么我会这样做:

#!/bin/bash
# Simple pangram tester.
# Doesn't handle non-alphabetic chars except space.
# Written by PM 2Ring 2014.10.21
is_pangram()
{
    count=$(echo -n ${1// /}|(while read -n 1 a;do echo $a;done)|sort -fu|wc -l)
    [[ $count -eq 26 ]]
}
test_pangram()
{
    if is_pangram "$1"
        then echo "'$1' is a pangram."
        else echo "'$1' is not a pangram."
    fi
}
teststrings=(
    "A quick brown fox jumps over the lazy dog"
    "This is a test" 
    "Cwm fjord bank glyphs vext quiz"
    "Is not a pangram"
)
for s in "${teststrings[@]}"
do
    test_pangram "$s"
done

最新更新