shell BASH:两条路径之间的路径差异?

uttx8gqw  于 12个月前  发布在  Shell
关注(0)|答案(2)|浏览(83)

说我有路

a/b/c/d/e/f
a/b/c/d

下面怎么走?

e/f
vql8enpb

vql8enpb1#

您可以使用以下命令将一个字符串从另一个字符串中剥离:

echo "${string1#"$string2"}"

请参阅:

$ string1="a/b/c/d/e/f"
$ string2="a/b/c/d"
$ echo "${string1#"$string2"}"
/e/f

man bash-> Shell parameter expansion
${parameter#word}
${参数##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
acruukt9

acruukt92#

另一个解决方案(从这个other related post)是:

$ realpath -m --relative-to=a/b/c/d a/b/c/d/e/f
e/f

它正确地处理空格(在这种情况下引用路径)和多个斜杠。
这里的选项-m只是为了避免在两个路径都不存在时出错。

相关问题