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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4411080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:04:34  来源:igfitidea点击:

How can I change the extension name in a string with bash?

bash

提问by prosseek

I want to translate the following python code to bash. The code changes the extension name to .html and runs Safari to open it.

我想将以下 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)

How can I change the file extension with bash?

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

回答by Ignacio Vazquez-Abrams

file=somefile.whatevs
open -a Safari "${file%.*}.html"

回答by dinigo

If you happen to know the extension you can switch it like this:

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

$ MY_FILE=file.html
$ NEW_EXT=${MY_FILE/html/php}
$ echo ${NEW_EXT}
file.php