string 在shell脚本中获取子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1208908/
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
get sub string in shell script
提问by derrdji
if I have a string like some/unknown/amount/of/sub/folder/file.txt
how can I get only the the file.txt
sub string, remove the front part, while the length is unknown.
如果我有一个字符串,比如some/unknown/amount/of/sub/folder/file.txt
如何只获取file.txt
子字符串,请删除前面的部分,而长度未知。
thank you
谢谢你
EDIT: file name could be any length, and sub folders could be any levels.
编辑:文件名可以是任意长度,子文件夹可以是任意级别。
采纳答案by Matthew Flaschen
Use basename
command:
使用basename
命令:
orig_path="some/unknown/amount/of/sub/folder/file.txt"
last_comp=$(basename $orig_path)
echo $last_comp
回答by Stefano Borini
$ basename "some/unknown/amount/of/sub/folder/file.txt"
file.txt
To generically extract a substring, you can use this syntax
要一般提取子字符串,您可以使用此语法
$ hello="abcdef"
$ echo ${hello:1:3}
bcd
回答by William Pursell
While I agree that the correct answer is to invoke basename, in bash you can also use ## to delete the longest occurrence of a string from the start of a variable.
虽然我同意正确的答案是调用 basename,但在 bash 中,您也可以使用 ## 从变量的开头删除最长出现的字符串。
bash-3.2$ t=/this/is/a/path bash-3.2$ echo ${t##*/} path
回答by Oleksandr Tymoshenko
basename some/unknown/amount/of/sub/folder/file.txt
basename some/unknown/amount/of/sub/folder/file.txt