String 获取shell脚本中的子字符串

String 获取shell脚本中的子字符串,string,shell,String,Shell,如果我有一个字符串,如some/unknown/amount/of/sub/folder/file.txt如何仅获取file.txt子字符串,在长度未知的情况下移除前面的部分 多谢各位 编辑:文件名可以是任意长度,子文件夹可以是任意级别。使用basename命令: orig_path="some/unknown/amount/of/sub/folder/file.txt" last_comp=$(basename $orig_path) echo $last_comp 要一般地提取子字符串,可

如果我有一个字符串,如
some/unknown/amount/of/sub/folder/file.txt
如何仅获取
file.txt
子字符串,在长度未知的情况下移除前面的部分

多谢各位


编辑:文件名可以是任意长度,子文件夹可以是任意级别。

使用
basename
命令:

orig_path="some/unknown/amount/of/sub/folder/file.txt"
last_comp=$(basename $orig_path)
echo $last_comp
要一般地提取子字符串,可以使用以下语法

$ hello="abcdef"
$ echo ${hello:1:3}
bcd

basename some/unknown/amount/of/sub/folder/file.txt

虽然我同意正确的答案是调用basename,但在bash中,您还可以使用###删除变量开头出现的最长字符串

bash-3.2$ t=/this/is/a/path bash-3.2$ echo ${t##*/} path bash-3.2$t=/this/is/a/path bash-3.2$echo${t##*/} 路径
呃…我不确定,GNU bash??这就是你要问的吗?o、 哦!! bash-3.2$ t=/this/is/a/path bash-3.2$ echo ${t##*/} path