这章主要介绍了shell脚本中常用的变量截取,涉及到##和%%
代码
file='/dir1/dir2/dir3/my.file.txt'
echo "The variable 'file' is ${file}."
echo "The command result of" '${file#*/}' "is ${file#*/}."
echo "The command result of" '${file##*/}' "is ${file##*/}."
echo "The command result of" '${file#*.}' "is ${file#*.}."
echo "The command result of" '${file##*.}' "is ${file##*.}."
echo "The command result of" '${file%/*}' "is ${file%/*}."
echo "The command result of" '${file%%/*}' "is ${file%%/*}."
echo "The command result of" '${file%.*}' "is ${file%.*}."
echo "The command result of" '${file%%.*}' "is ${file%%.*}."
echo "The command result of" '${#file}' "is ${#file}."
结果如下
The varialbe 'file' is /dir1/dir2/dir3/my.file.txt.
The command result of ${file#*/} is dir1/dir2/dir3/my.file.txt.
The command result of ${file##*/} is my.file.txt.
The command result of ${file#*.} is file.txt.
The command result of ${file##*.} is txt.
The command result of ${file%/*} is /dir1/dir2/dir3.
The command result of ${file%%/*} is .
The command result of ${file%.*} is /dir1/dir2/dir3/my.file.
The command result of ${file%%.*} is /dir1/dir2/dir3/my.
The command result of ${#file} is 27.
解释:
${file#*/}:删掉第一个 / 及其左边的字符串
${file##*/}:删掉最后一个/及其左边的字符串
${file##*/}:删掉最后一个 / 及其左边的字符串
${file#*.}:删掉第一个 . 及其左边的字符串
${file##*.}:删掉最后一个 . 及其左边的字符串
${file%/*}:删掉最后一个 / 及其右边的字符串
${file%%/*}:删掉第一个 / 及其右边的字符串
${file%.*}:删掉最后一个 . 及其右边的字符串
${file%%.*}:删掉第一个 . 及其右边的字符串
${#file}:求变量长度