使用 sed 删除路径字符串的最后一个 /

KK2*_*486 5 shell sed

我正在尝试使用 sed 替换以下目录结构中的最后一个 / ,但我无法成功。有什么建议?

输入是/tmp/ABC/Dirs/,输出应该是/tmp/ABC/Dirs

echo " /tmp/ABC/Dirs/"  | sed -r "s/\/(?:[a-zA-Z0-9])/g"
Run Code Online (Sandbox Code Playgroud)

noh*_*ide 8

sed这里似乎有点矫枉过正,您可以/直接在 Korn shell 中删除尾随(以及类似的 shell bash,以及所有 POSIX 兼容的 shell,因为 POSIX 已为该sh实用程序指定了 Korn shell 功能):

$ foo=/tmp/ABC/Dirs/
$ echo "${foo%/}"
/tmp/ABC/Dirs
Run Code Online (Sandbox Code Playgroud)


Ale*_*ies 1

我是第一个用我的评论回答问题的人s/\/$//

那天其他人有时间提供更全面的答案。

所以今天 - 几天后 - 我发布了一个多余的答案,因为我希望“同侪压力”铜奖从列表中消失。

sed -e s./$..g   # You can golf the quotes and the "\" here
Run Code Online (Sandbox Code Playgroud)

所以请各位好心人这次投反对票直到 -3 :)