【问题标题】:Getting file names in unix在 unix 中获取文件名
【发布时间】:2013-09-27 12:27:21
【问题描述】:

我有一个这样的脚本:

for html in ./templates/*.html
do
    # Here I need only the file name without extension.
done

如何在循环中只获取没有扩展名的文件名?

编辑:我对 UNIX 很陌生。

【问题讨论】:

标签: shell unix


【解决方案1】:

使用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)"
  • 这是返回我 default_template.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
  • 我明白了。谢谢你:)
【解决方案2】:

要仅删除扩展名并保留路径和名称,请使用正确的模式匹配运算符:

for f in ./templates/*.html; do
    echo ${f%%.html}
done

%% 运算符匹配从变量右侧开始的子字符串,并返回其余部分。所以它有效地匹配并去除了后缀,这对于文件扩展非常有用。

所以./templates/index.html 将简单地返回./templates/index。您可以根据需要添加自己的后缀或扩展名。

这比为每个文件调用basename 效率更高,因为它避免了产生另一个进程的开销。

【讨论】:

    【解决方案3】:

    试试这个

    对于 ./templates/*.html 中的 html 做 echo $html|sed 's/\.[a-zA-Z]*$//g'; 完毕

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 2012-01-11
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多