0

if[ xxx ]

how to expresss the string or file include '.'

I am new to study shell,thanks for any help

guosheng1987
  • 107
  • 1
  • 7

3 Answers3

3

You can use the matching operator:

$ if [[ "abc.def" =~ \. ]]; then echo "yes"; else echo "no"; fi
yes

$ if [[ "abcdef" =~ \. ]]; then echo "yes"; else echo "no"; fi
no

This matches if the dot is the first or last (or only) character in the string. If you expect characters on both sides of the dot, you can do the following:

$ if [[ "ab.cdef" =~ .\.. ]]; then echo "yes"; else echo "no"; fi
yes

$ if [[ ".abcdef" =~ .\.. ]]; then echo "yes"; else echo "no"; fi
no

$ if [[ "abcdef." =~ .\.. ]]; then echo "yes"; else echo "no"; fi
no

You can also use pattern matching:

$ if [[ "ab.cdef" == *?.?* ]]; then echo "yes"; else echo "no"; fi
yes

$ if [[ ".abcdef" == *?.?* ]]; then echo "yes"; else echo "no"; fi
no

$ if [[ "abcdef." == *?.?* ]]; then echo "yes"; else echo "no"; fi
no

A good reference for both patterns and regexes is at Greg's Wiki

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
2

bash supports glob-style pattern matching:

if [[ "$file" = *?.?* ]]; then
   ...
fi

Note that this assumes a prefix as well - this also ensures that it will not match the . and .. directories.

If you want to check for a specific extension:

if [[ "$file" = *?.foo ]]; then
   ...
fi
thkala
  • 84,049
  • 23
  • 157
  • 201
-2
echo "xxx.yyy" | grep -q '\.'
if [ $? = 0 ] ; then
    # do stuff
fi

Or

echo "xxx.yyy" | grep -q '\.' && <one statement here>
#e.g.
echo "xxx.yyy" | grep -q '\.' && echo "got a dot"
John3136
  • 28,809
  • 4
  • 51
  • 69
  • 2
    Not only this is inefficient, since it launches an additional process (`grep`), but it is also incorrect: in regular expressions a single un-escaped dot matches every character. Perhaps you meant `'\.'` instead of `'.'`? – thkala Jul 05 '12 at 09:13
  • Correct. I was under the impression that the single quotes removed the regex-ness - it doesn't. '.' needs to be escaped. – John3136 Jul 06 '12 at 00:53