shell脚本判断文件后缀
有时候需要判断文件名后缀来区分文件类型,进而进行不同的操作。以下是获取文件名后缀和文件名前缀的两个函数,由于shell脚本函数只能返回0-255,为了将结果返回,就直接使用echo输出,可以用$()进行捕获。
- #!/bin/bash
-
- # --------------------------------------------------------------------------- #
- # 获取文件名后缀
- # Parameter1: 文件名
- # output: Yes
- # return: None
- # --------------------------------------------------------------------------- #
- function FileSuffix() {
- local filename="$1"
- if [ -n "$filename" ]; then
- echo "${filename##*.}"
- fi
- }
-
- # --------------------------------------------------------------------------- #
- # 获取文件名前缀
- # Parameter1: 文件名
- # output: Yes
- # return: None
- # --------------------------------------------------------------------------- #
- function FilePrefix() {
- local filename="$1"
- if [ -n "$filename" ]; then
- echo "${filename%.*}"
- fi
- }
-
使用示例:
- # --------------------------------------------------------------------------- #
- # 判断文件后缀是否是指定后缀
- # Parameter1: 文件名
- # parameter2: 后缀名
- # output: None
- # return: 0: 表示文件后缀是指定后缀;1: 表示文件后缀不是指定后缀
- # --------------------------------------------------------------------------- #
- function IsSuffix() {
- local filename="$1"
- local suffix="$2"
- if [ "$(FileSuffix ${filename})" = "$suffix" ]; then
- return 0
- else
- return 1
- fi
- }
-
- file="demo.txt"
-
- IsSuffix ${file} "txt"
- ret=$?
-
- if [ $ret -eq 0 ]; then
- echo "the suffix of the ${file} is txt"
- fi
附shell提取文件后缀名,并判断其是否为特定字符串
如果文件是 .css文件 或 .js文件,则进行处理。
- file=$1
- if [ "${file##*.}"x = "css"x ]||[ "${file##*.}"x = "js"x ];then
-
- ? ? do something
- fi
注意:
1> 提取文件后缀名: ${file##*.}
##是贪婪操作符,从左至右匹配,匹配到最右边的.号,移除包含.号的左边内容。
2> 是=,而且其两边有空格,如果没有空格,会报错
3> 多加了x,是为了防止字符串为空时报错。
查找当前目录下文件名中包含.py,.sh,.css,.js,.html时,
- for n in `find . -name "*.py" -o -name "*.sh" -o -name "*.css" -o -name "*.js" -o -name "*.html"`; do
-
- ? ?something
- done
注意:
1> 查找当前目录下文件名末尾字符为.py,或.sh,或.css,或.js,或.html的文件,并处理
总结
到此这篇关于使用shell脚本判断文件后缀的文章就介绍到这了,更多相关shell脚本判断文件后缀内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!