2

I want to check whether a string has at least one alphabetic character? a regex could be like:

"^.*[a-zA-Z].*$"

however, I want to judge whether a string has at least one alphabetic character? so I want to use, like

 if [ it contains at least one alphabetic character];then
 ...
 else
 ...
 fi

so I'm at a loss on how to use the regex

I tried

if [ "$x"=~[a-zA-Z]+ ];then echo "yes"; else echo "no" ;fi
or
if [ "$x"=~"^.*[a-zA-Z].*$" ];then echo "yes"; else echo "no" ;fi

and test with x="1234", both of the above script output result of "yes", so they are wrong

how to achieve my goal?thanks!

Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62
user1944267
  • 1,557
  • 5
  • 20
  • 27
  • 1
    I think you're looking for [this](http://stackoverflow.com/questions/304864/how-do-i-use-regular-expressions-in-bash-scripts). – David Jan 02 '13 at 23:41
  • 1
    There are two problems: you need to use `[[` and `]]` instead of `[` and `]`; and you need to have spaces around the `=~` operator, otherwise bash sees it as part of one single long string. – Anders Johansson Jan 03 '13 at 00:14
  • @Anders Johansson, you are right, it is ok now, but why do I need double [], can you explain this a bit? thanks! – user1944267 Jan 03 '13 at 00:27
  • @user1944267, the `[` builtin (see `man [`) is much less powerful than `[[` (see `man bash`; for example `[[` supports more operators and natural constructs like `&&` and `||` with their usual meaning while `[` requires `-a` and `-o` with explicit parentheses to get the same result). The `=~` operator only exists in `[[`. – Anders Johansson Jan 03 '13 at 00:38

4 Answers4

3

Try this:

 #!/bin/bash

x="1234"
y="a1234"

if [[ "$x" =~ [A-Za-z] ]]; then
        echo "$x has one alphabet"
fi

if [[ "$y" =~ [A-Za-z] ]]; then
        echo "Y is $y and has at least one alphabet"
fi
abhi.gupta200297
  • 881
  • 6
  • 12
2

If you want to be portable, I'd call /usr/bin/grep with [A-Za-z].

hd1
  • 33,938
  • 5
  • 80
  • 91
0

Use the [:alpha:] character class that respects your locale, with a regular expression

[[ $str =~ [[:alpha:]] ]] && echo has alphabetic char

or a glob-style pattern

[[ $str == *[[:alpha:]]* ]] && echo has alphabetic char
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

It's quite common in sh scripts to use grep in an if clause. You can find many such examples in /etc/rc.d/.

if echo $theinputstring | grep -q '[a-zA-Z]' ; then
    echo yes
else
    echo no
fi
Wu Yongzheng
  • 1,707
  • 17
  • 23