How can I check if a variable is contains only letters

☆樱花仙子☆ 提交于 2021-02-10 12:29:28

问题


I tried to check the following case:

#!/bin/bash

line="abc"

if [[ "${line}" != [a-z] ]]; then
   echo INVALID
fi

And I get INVALID as output. But why?
It's no check if $line contains only a characters in the range [a-z] ?


回答1:


Use the regular expression matching operator =~:

#!/bin/bash

line="abc"

if [[ "${line}" =~ [^a-zA-Z] ]]; then
   echo INVALID
fi



回答2:


Works in any Bourne shell and wastes no pipes/forks:

case $var in
   ("")       echo "empty";;
   (*[!a-z]*) echo "contains a non-alphabetic";;
   (*)        echo "just alphabetics";;
esac

Use [!a-zA-Z] if you want to allow upper case as well.




回答3:


Could you please try following and let me know if this helps you.

line="abc"
if  echo "$line" | grep -i -q '^[a-z]*$'
then
        echo "MATCHED."
else
        echo "NOT-MATCHED."
fi



回答4:


Pattern matches are anchored to the beginning and end of the string, so your code checks if $line is not a single lowercase character. You want to match an arbitrary sequence of lowercase characters, which you can do using extended patterns:

if [[ $line != @([a-z]) ]]; then

or using the regular-expression operator:

if ! [[ $line =~ ^[a-z]+$ ]]; then  # there is no negative regex operator like Perl's !~



回答5:


Why? Because != means "not equal", thats why. You tell bash to compare abc with [a-z]. They are not equal.

Try echo $line | grep -i -q -x '[a-z]*'.

The flag -i makes grep case insensitive. The flag -x means match the whole line. The flag -q means print nothing to stdout, just return 1 or 0.



来源:https://stackoverflow.com/questions/51349938/how-can-i-check-if-a-variable-is-contains-only-letters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!