Shell获取目录下文件名、后缀并操作

1.文件名、文件后缀获取.

已有文件  FILE= "example.tar.gz",获取文件名和文件后缀方式如下:
 
echo "${FILE%%.*}"
# => example
 
echo "${FILE%.*}"
# => example.tar
 
echo "${FILE#*.}"
# => tar.gz
 
echo "${FILE##*.}"
# => gz

2.对目录下特定文件类型进行操作

选定某目录下文件后缀为.sh的文件,将其改为后缀为.c的文件,脚本如下

#!/bin/bash

for file in $(ls ./)
do 
    if [ "${file##*.}" = "sh" ]; then
        mv ${file} ${file%.*}.c
    fi
done

注意点:在shell语句判断中 [ "${file##*.}" = "sh" ]  等号两边都要有空格,等号两边变量需要用“”,中括号两边要有空格。

猜你喜欢

转载自www.cnblogs.com/kuangsyx/p/12595888.html