如何从 Bash 中的路径字符串中删除文件后缀和路径部分? [英] How do I remove the file suffix and path portion from a path string in Bash?
本文介绍了如何从 Bash 中的路径字符串中删除文件后缀和路径部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个字符串文件路径,例如 /foo/fizzbuzz.bar
,我将如何使用 bash 只提取所述字符串的 fizzbuzz
部分?
Given a string file path such as /foo/fizzbuzz.bar
, how would I use bash to extract just the fizzbuzz
portion of said string?
推荐答案
这里是如何使用 Bash 中的 # 和 % 运算符来实现的.
Here's how to do it with the # and % operators in Bash.
$ x="/foo/fizzbuzz.bar"
$ y=${x%.bar}
$ echo ${y##*/}
fizzbuzz
${x%.bar}
也可以是 ${x%.*}
以删除点或 ${x%% 之后的所有内容.*}
删除第一个点之后的所有内容.
${x%.bar}
could also be ${x%.*}
to remove everything after a dot or ${x%%.*}
to remove everything after the first dot.
示例:
$ x="/foo/fizzbuzz.bar.quux"
$ y=${x%.*}
$ echo $y
/foo/fizzbuzz.bar
$ y=${x%%.*}
$ echo $y
/foo/fizzbuzz
文档可以在 Bash 手册.查找 ${parameter%word}
和 ${parameter%%word}
尾部匹配部分.
Documentation can be found in the Bash manual. Look for ${parameter%word}
and ${parameter%%word}
trailing portion matching section.
这篇关于如何从 Bash 中的路径字符串中删除文件后缀和路径部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文