19

I have this

echo $line
Thisisaline.

I was wondering why is this not working:

if [[ "$line" =~ "[a-zA-Z]+\.$" ]] ; then echo "hello"; fi

Above regex gives no output.

doubleDown
  • 8,048
  • 1
  • 32
  • 48
Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208

3 Answers3

27

The problem is that you are using quotes...

In bash regex, there is no need for quotes, and moreso, they should not be used (unless you are trying to match a quote (in which case you can escape it \")... Also if you want a space in your pattern, you must escape it, (there is a space after the back-slash ...

Also note, that to match the entire line as being alphabetic, you must add a leading ^ and a trailing $, otherwise it will match such lines as: 123 456 abc. cat and mouse

Peter.O
  • 6,696
  • 4
  • 30
  • 37
14

Try

if [[ $line =~ [a-zA-Z]+\. ]] ; then echo hello; fi
user unknown
  • 35,537
  • 11
  • 75
  • 121
2

Some version of OS with bash gives you the output. So its up to you to get your updates. However, without regex you can use extended globbing

shopt -s extglob
case "$line" in
+([a-zA-Z]). ) echo "hello";;
esac

if not, use regex without the quotes

ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • Yes +1, it is the quotes.. They are not needed, and moreso, should not be used here (unless you are trying to match a quote; so if you want a space in your pattern, you must escape it, `\ ` (there is a space after the \ ... Also note, that to match the entire line as alphabetic, you must ad a leading `^` and a trailing `$`, otherwise it will match `123 456 abc. cat and mouse` – Peter.O May 01 '11 at 07:59
  • @fred, ok, so you should put that up as an answer so OP can know. :) – ghostdog74 May 01 '11 at 08:07