如何使用bash更改字符串中的扩展名?

pro*_*eek 33 bash

我想将以下python代码翻译为bash.代码将扩展名更改为.html并运行Safari以打开它.

#!/usr/bin/env python
import os.path
import os

oldName = $TM_FILEPATH
(name, ext) = os.path.splitext(oldName)
rename = name + ".html"
os.system("open -a Safari %s" % rename)
Run Code Online (Sandbox Code Playgroud)

如何使用bash更改文件扩展名?

Ign*_*ams 80

file=somefile.whatevs
open -a Safari "${file%.*}.html"
Run Code Online (Sandbox Code Playgroud)

  • 哇,那很优雅. (3认同)
  • 在 [superuser](https://superuser.com/a/1119299/347427) 上有一个很好的解释:“当 `%` 用于模式 `${variable%substring}` 时,它将返回变量的内容从变量后面删除的子串的最短出现。” (3认同)

din*_*igo 10

如果您碰巧知道扩展名,您可以像这样切换它:

$ MY_FILE=file.html
$ NEW_EXT=${MY_FILE/html/php}
$ echo ${NEW_EXT}
file.php
Run Code Online (Sandbox Code Playgroud)

  • 如果它的名称是 my_html_file.html 并且我想获取 my_html_file.php 怎么办? (2认同)