UNIX中的模式匹配说明

时间:2014-03-14 11:36:25

标签: bash shell

我有一个脚本如下:

for file in *.txt
do
    mv "$file" "${file%_*}.txt"
done

此脚本将文件CC_something_xyzgh_hh_ABCDEF.txt重命名为CC_something_xyzgh_hh.txt。但我不清楚到底是做什么的。

我在网上搜索过,但找不到任何能回答我问题的内容。

有人可以帮我吗?

2 个答案:

答案 0 :(得分:2)

你在这里基本上做的是shell parameter expansion

${file%_*}从末尾删除扩展值的最短匹配模式。例如:

$ for file in *.txt; do echo "$file =====> ${file%_*}.txt"; done
CC_something_xyzgh_hh_ABCDEF.txt =====> CC_something_xyzgh_hh.txt

同样,要从最后删除最长匹配 ,您可以使用%%

$ for file in *.txt; do echo "$file =====> ${file%%_*}.txt"; done 
CC_something_xyzgh_hh_ABCDEF.txt =====> CC.txt

要从开始的做类似的事情,您可以使用#(最短)和##(最长)

$ for file in *.txt; do echo "$file =====> ${file#*_}.txt"; done
CC_something_xyzgh_hh_ABCDEF.txt =====> something_xyzgh_hh_ABCDEF.txt.txt

$ for file in *.txt; do echo "$file =====> ${file##*_}.txt"; done
CC_something_xyzgh_hh_ABCDEF.txt =====> ABCDEF.txt.txt

答案 1 :(得分:1)

${string%substring}

    Deletes shortest match of $substring from back of $string.

示例:

sat:~# file="CC_something_xyzgh_hh_ABCDEF.txt"
sat:~# echo ${file%_*}
CC_something_xyzgh_hh