说我有路
a/b/c/d/e/f a/b/c/d
下面怎么走?
e/f
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}单词被扩展以产生一种模式,就像文件名扩展一样。如果模式匹配参数的扩展值的开始,则扩展的结果是删除了最短匹配模式(“#”情况)或最长匹配模式(“##”情况)的参数的扩展值。有空格:
man bash
$ string1="hello/i am here/foo/bar" $ string2="hello/i am here/foo" $ echo "${string1#"$string2"}" /bar
要“清理”多个斜杠,可以遵循Roberto Reale的建议,用readlink -m规范化路径,以允许与具有相同实际路径的字符串进行比较:
readlink -m
$ string1="/a///b/c//d/e/f/" $ readlink -m $string1 /a/b/c/d/e/f
acruukt92#
另一个解决方案(从这个other related post)是:
$ realpath -m --relative-to=a/b/c/d a/b/c/d/e/f e/f
它正确地处理空格(在这种情况下引用路径)和多个斜杠。这里的选项-m只是为了避免在两个路径都不存在时出错。
-m
2条答案
按热度按时间vql8enpb1#
您可以使用以下命令将一个字符串从另一个字符串中剥离:
请参阅:
从
man bash
-> Shell parameter expansion:${parameter#word}
${参数##word}
单词被扩展以产生一种模式,就像文件名扩展一样。如果模式匹配参数的扩展值的开始,则扩展的结果是删除了最短匹配模式(“#”情况)或最长匹配模式(“##”情况)的参数的扩展值。
有空格:
要“清理”多个斜杠,可以遵循Roberto Reale的建议,用
readlink -m
规范化路径,以允许与具有相同实际路径的字符串进行比较:acruukt92#
另一个解决方案(从这个other related post)是:
它正确地处理空格(在这种情况下引用路径)和多个斜杠。
这里的选项
-m
只是为了避免在两个路径都不存在时出错。