bash 仅从文件名中删除最后一个扩展名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18251070/
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
remove only the last extension from file name
提问by user1958508
I have file names that look something similar to this
我的文件名看起来与此类似
name_1.23.ps.png
or
或者
name_1.23.ps.best
or
或者
name_1.23.ps
I want to take off the random file extensions on the end and be left with just
我想去掉最后的随机文件扩展名,只剩下
name_1.23.ps
Other questions similar to this use '.' as a delimator but this removes everything after name_1.
与此类似的其他问题使用“.” 作为分隔符,但这会删除 name_1 之后的所有内容。
I want to do this on the command line (in tcsh or bash)
我想在命令行上执行此操作(在 tcsh 或 bash 中)
回答by burnabyRails
We can use the bash string operation that deletes the shortest match of a glob patten from the back of a string. We will use ".*" for the glob pattern.
我们可以使用 bash 字符串操作从字符串的后面删除全局模式的最短匹配项。我们将使用“.*”作为 glob 模式。
filename="name_1.23.ps.png"
echo ${filename%.*}
# the above output name_1.23.ps
This answer is more for my own reference as I come back to this page a few times. (It does not satisfy the OP's additional requirement of keeping the original string the same if it ends with only '.ps').
当我多次返回此页面时,此答案更适合我自己的参考。(如果它仅以“.ps”结尾,则它不满足 OP 保持原始字符串相同的附加要求)。
回答by Kent
check this if it works for your requirement:
检查它是否适合您的要求:
sed
sed
sed 's/\.[^.]*$//'
grep
格雷普
grep -Po '.*(?=\.)'
test:
测试:
kent$ cat f
name_1.23.ps.png
name_1.23.ps.best
name_1.23.ps
name_1.23.ps
#sed:
kent$ sed 's/\.[^.]*$//' f
name_1.23.ps
name_1.23.ps
name_1.23
name_1.23
#grep
kent$ grep -Po '.*(?=\.)' f
name_1.23.ps
name_1.23.ps
name_1.23
name_1.23
EDITfrom the comments. I feel it would be new requirement:
从评论中编辑。我觉得这将是新的要求:
grep
格雷普
kent$ grep -o '.*\.ps' f
name_1.23.ps
name_1.23.ps
name_1.23.ps
name_1.23.ps
sed
sed
kent$ sed 's/\(.*\.ps\)\..*//' f
name_1.23.ps
name_1.23.ps
name_1.23.ps
name_1.23.ps
回答by Alex Filipovici
Try this:
尝试这个:
string="name_1.23.ps.png"
array=(${string//./ })
echo "${array[0]}.${array[1]}.${array[2]}"