说我有路径
a/b/c/d/e/f
a/b/c/d
如何获得以下内容?
e/f
您可以使用以下方法将一根绳子从另一根绳子上剥离:
echo "${string1#"$string2"}"
参见:
$ string1="a/b/c/d/e/f"
$ string2="a/b/c/d"
$ echo "${string1#"$string2"}"
/e/f
来自
man bash
-> Shell 参数扩展:
${参数#word}
${参数##字}
该单词被扩展以产生一个模式,就像文件名中一样 扩张。如果模式与扩展值的开头匹配 参数,那么展开的结果就是展开后的值 具有最短匹配模式(“#”大小写)的参数或 最长匹配模式(“##”大小写)已删除。
有空格:
$ string1="hello/i am here/foo/bar"
$ string2="hello/i am here/foo"
$ echo "${string1#"$string2"}"
/bar
要“清理”多个斜杠,您可以遵循 Roberto Reale 的建议,并使用
readlink -m
规范化路径,以允许与具有相同实际路径的字符串进行比较:
$ string1="/a///b/c//d/e/f/"
$ readlink -m $string1
/a/b/c/d/e/f
另一个解决方案(来自此其他相关帖子)是:
$ realpath -m --relative-to=a/b/c/d a/b/c/d/e/f
e/f
它可以正确处理空格(在这种情况下引用路径)和多个斜杠。