bash 从每个参数中删除尾部斜杠的最简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9018723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the simplest way to remove a trailing slash from each parameter?
提问by sid_com
What is the simplest way to remove a trailing slash from each parameter in the '$@' array, so that rsync
copies the directories by name?
从 '$@' 数组中的每个参数中删除尾部斜杠,以便rsync
按名称复制目录的最简单方法是什么?
rsync -a --exclude='*~' "$@" "$dir"
The title has been changed for clarification. To understand the comments and answer about multiple trailing slashes see the edit history.
为了澄清起见,标题已更改。要了解有关多个尾部斜杠的评论和答案,请参阅编辑历史记录。
回答by Sean Bright
回答by Chris Johnson
The accepted answer will trim ONE trailing slash.
接受的答案将修剪一个尾部斜杠。
One way to trim multiple trailing slashes is like this:
修剪多个尾部斜杠的一种方法是这样的:
VALUE=/looks/like/a/path///
TRIMMED=$(echo $VALUE | sed 's:/*$::')
echo $VALUE $TRIMMED
Which outputs:
哪些输出:
/looks/like/a/path/// /looks/like/a/path
回答by Ivan
This works for me: ${VAR%%+(/)}
这对我有用: ${VAR%%+(/)}
As described here http://wiki.bash-hackers.org/syntax/pattern
如此处所述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
可能需要设置 shell 选项 extglob。我看不到它为我启用,但它仍然有效
回答by czerny
realpath
resolves given path. Among other things it also removes trailing slashes. Use -s
to prevent following simlinks
realpath
解析给定的路径。除其他外,它还删除了尾部斜杠。使用-s
防止以下simlinks
DIR=/tmp/a///
echo $(realpath -s $DIR)
# output: /tmp/a
回答by Jonathan H
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.
仅供参考,我.bash_profile
根据在 SO 上找到的答案将这两个函数添加到我的。正如 Chris Johnson 所说,所有使用的答案${x%/}
都只删除一个斜线,这些功能会按照他们说的做,希望这有用。
rem_trailing_slash() {
echo | sed 's/\/*$//g'
}
force_trailing_slash() {
echo $(rem_trailing_slash )/
}
回答by Nicolai Fr?hlich
In zshyou can use the :a
modifier.
在zsh 中,您可以使用:a
修饰符。
export DIRECTORY='/some//path/name//'
echo "${DIRECTORY:a}"
=> /some/path/name
This acts like realpath
but doesn't fail with missing files/directories as argument.
这就像realpath
但不会因丢失文件/目录作为参数而失败。