我有一部分 bash 脚本正在获取不带扩展名的文件名,但我试图了解这里到底发生了什么。“%%”是干什么用的?有人可以详细说明 bash 在幕后做什么吗?如何在一般基础上使用这种技术?
#!/bin/bash
for src in *.tif
do
txt=${src%%.*}
tesseract ${src} ${txt}
done
它摆脱了文件扩展名(这里: .tif
),示例:
$ for A in test.py test.sh test.xml test.xsl; do echo "$A: ${A%%.*}"; done
test.py: test
test.sh: test
test.xml: test
test.xsl: test
来自 bash 手册:
${parameter%%word}
The word is expanded to produce a pattern just as in pathname expansion. If the
pattern matches a trailing portion of the expanded value of parameter, then the
result of the expansion is the expanded value of parameter with the shortest
matching pattern (the ``%'' case) or the longest matching pattern (the ``%%''
case) deleted. If parameter is @ or *, the pattern removal operation is applied
to each positional parameter in turn, and the expansion is the resultant list.
If parameter is an array variable subscripted with @ or *, the pattern removal
operation is applied to each member of the array in turn, and the expansion is
the resultant list.
这是 bash 手册页的输出
${parameter%%word}
The word is expanded to produce a pattern just as in pathname
expansion. If the pattern matches a trailing portion of the
expanded value of parameter, then the result of the expansion is
the expanded value of parameter with the shortest matching pat-
tern (the ``%'' case) or the longest matching pattern (the
``%%'' case) deleted. If parameter is @ or *, the pattern
removal operation is applied to each positional parameter in
turn, and the expansion is the resultant list. If parameter is
an array variable subscripted with @ or *, the pattern removal
operation is applied to each member of the array in turn, and
the expansion is the resultant list.
显然 bash 有几个“参数扩展”工具,其中包括:
只需替换值...
${parameter}
扩展为子字符串...
${parameter:offset}
${parameter:offset:length}
代入参数值的长度...
${#parameter}
扩展参数开头的匹配...
${parameter#word}
${parameter##word}
扩展参数末尾的匹配...
${parameter%word}
${parameter%%word}
扩展参数以查找和替换字符串...
${parameter/pattern/string}
这些是我对我认为从手册页的这一部分中理解的部分的解释。如果我错过了重要的事情,请告诉我。
查看 bash 手册页中的“参数扩展”。该语法扩展了 $src 变量,从中删除了与 .* 模式匹配的内容。
这是一个字符串删除操作,格式如下:${str%%substr}
其中 str 是您正在操作的字符串,而 substr 是要匹配的模式。它在 str 中查找 substr 的最长匹配,并从那时起删除所有内容。