字符串包含字符bash

时间:2014-10-21 01:37:55

标签: bash if-statement echo glob pangram

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"的输出。 有谁知道我的代码出了什么问题?

我试图操纵the code from a previous question of mine.

3 个答案:

答案 0 :(得分:2)

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

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

此函数首先将其参数转换为小写:${1,,}的扩展是$1转换为小写的扩展;我们将此值存储在局部变量l中。然后我们使用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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

您可以使用常见的* 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