how to use if to see whether file has suffix in shell bash script
This question already has an answer here:
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
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
echo "xxx.yyy" | grep -q '.'
if [ $? = 0 ] ; then
# do stuff
fi
要么
echo "xxx.yyy" | grep -q '.' && <one statement here>
#e.g.
echo "xxx.yyy" | grep -q '.' && echo "got a dot"
链接地址: http://www.djcxy.com/p/36190.html