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

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

get sub string in shell script

stringshell

提问by derrdji

if I have a string like some/unknown/amount/of/sub/folder/file.txthow can I get only the the file.txtsub 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 basenamecommand:

使用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