从每个参数中删除尾部斜杠的最简单方法是什么?
从 '$@' 数组中的每个参数中删除尾部斜杠,以便 rsync 按名称复制目录的最简单方法是什么?
rsync -a --exclude='*~' "$@" "$dir"
为了澄清起见,标题已更改。要了解有关多个尾部斜杠的评论和答案,请参阅编辑历史记录。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
您可以使用 此处。这是一个演示该行为的简单测试脚本:
You can use the
${parameter%word}
expansion that is detailed here. Here is a simple test script that demonstrates the behavior:接受的答案将修剪一个尾部斜杠。
修剪多个尾部斜杠的一种方法如下:
哪个输出:
The accepted answer will trim ONE trailing slash.
One way to trim multiple trailing slashes is like this:
Which outputs:
这对我有用:
${VAR%%+(/)}
如此处所述 http://wiki.bash-hackers.org/syntax/pattern
可能需要设置 shell 选项 extglob。我看不到它为我启用,但它仍然有效
This works for me:
${VAR%%+(/)}
As described here http://wiki.bash-hackers.org/syntax/pattern
May need to set the shell option extglob. I can't see it enabled for me but it still works
realpath
解析给定的路径。除此之外,它还删除了尾部斜杠。使用-s
防止跟随 simlinksrealpath
resolves given path. Among other things it also removes trailing slashes. Use-s
to prevent following simlinks仅供参考,我根据在 SO 上找到的答案将这两个函数添加到我的
.bash_profile
中。正如 Chris Johnson 所说,所有使用${x%/}
的答案仅删除一个斜杠,这些函数将执行它们所说的操作,希望这有用。FYI, I added these two functions to my
.bash_profile
based on the answers found on SO. As Chris Johnson said, all answers using${x%/}
remove only one slash, these functions will do what they say, hope this is useful.在 zsh 中,您可以使用
:a
修饰符。这与
realpath
类似,但不会因缺少文件/目录作为参数而失败。In zsh you can use the
:a
modifier.This acts like
realpath
but doesn't fail with missing files/directories as argument.我在修剪用于 rsync 的目录参数时使用的方法,这里使用 dirname 和 basename 来分割路径,然后重新组合各个部分没有尾部斜杠。
Approach I have used, when trimming directory arguments that are intended for
rsync
, here usingdirname
andbasename
to split the path and then recombining the parts without the trailing slash.完全符合 POSIX 标准
Completely POSIX compliant
记下已接受答案中的几条评论:
//[...]
替换为单个斜杠/
(根据@Dave 评论)/
)(根据 @GordonDavisson 评论)不像使用参数替换的答案那么简洁,但我认为它值得付出努力。
一些测试用例:
Taking note of a couple comments in the accepted answer:
//[...]
with a single slash/
(per @Dave comment)/
) (per @GordonDavisson comment)Not as concise as the answers using parameter substitution, but I think its worth the diligence.
Some test cases:
这不是最漂亮的方式,但又快又简单。
我只是添加一个斜杠并删除所有双打。假设在其他地方找不到这样的模式。
Not the most beautiful way, but quick and easy.
I just add a slash and remove all doubles. Assuming such a pattern will not be found elsewhere.