0

if[ xxx ]

how to expresss the string or file include '.'

I am new to study shell,thanks for any help

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

4 Comments

You can omit the plus signs, .\.. is sufficient.
You don't need to use an RE, shell pattern matching will do.
@DennisWilliamson +1 thanks for that, you are of course right. I've improved the answer with your suggestion.
@cdarke +1 thanks. Very true. I've added this to the answer.
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

Comments

-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"

2 Comments

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 '.'?
Correct. I was under the impression that the single quotes removed the regex-ness - it doesn't. '.' needs to be escaped.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.