【发布时间】:2013-09-27 12:27:21
【问题描述】:
我有一个这样的脚本:
for html in ./templates/*.html
do
# Here I need only the file name without extension.
done
如何在循环中只获取没有扩展名的文件名?
编辑:我对 UNIX 很陌生。
【问题讨论】:
-
C 语言或 shell 脚本
我有一个这样的脚本:
for html in ./templates/*.html
do
# Here I need only the file name without extension.
done
如何在循环中只获取没有扩展名的文件名?
编辑:我对 UNIX 很陌生。
【问题讨论】:
使用basename:
basename "$html" .html
或者,可以使用 bash 正则表达式将路径分解为目录前缀、基本名称和文件后缀:
$ [[ "/usr/share/doc/bzip2-devel-1.0.6/manual.html" =~ (.+/)?([^/]+)(\.[^/]+) ]]; echo ${BASH_REMATCH[*]}
/usr/share/doc/bzip2-devel-1.0.6/manual.html /usr/share/doc/bzip2-devel-1.0.6/ manual .html
^ ^ ^ ^
| | | |
entire string directory base suffix
【讨论】:
"$(basename "$html" .html)"。
info basename If SUFFIX is specified and is identical to the end of NAME, it is removed from NAME as well. 所以你需要像@Alfe提到的那样打电话,basename $html .html
要仅删除扩展名并保留路径和名称,请使用正确的模式匹配运算符:
for f in ./templates/*.html; do
echo ${f%%.html}
done
%% 运算符匹配从变量右侧开始的子字符串,并返回其余部分。所以它有效地匹配并去除了后缀,这对于文件扩展非常有用。
所以./templates/index.html 将简单地返回./templates/index。您可以根据需要添加自己的后缀或扩展名。
这比为每个文件调用basename 效率更高,因为它避免了产生另一个进程的开销。
【讨论】:
试试这个
对于 ./templates/*.html 中的 html 做 echo $html|sed 's/\.[a-zA-Z]*$//g'; 完毕【讨论】: