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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:35:09  来源:igfitidea点击:

What is the simplest way to remove a trailing slash from each parameter?

bashshellargumentsrsyncstripslashes

提问by sid_com

What is the simplest way to remove a trailing slash from each parameter in the '$@' array, so that rsynccopies 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

You can use the ${parameter%word}expansion that is detailed here. Here is a simple test script that demonstrates the behavior:

您可以使用此处${parameter%word}详述的扩展。这是一个演示行为的简单测试脚本:

#!/bin/bash

# Call this as:
#   ./test.sh one/ two/ three/ 
#
# Output:
#  one two three

echo ${@%/}

回答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

realpathresolves given path. Among other things it also removes trailing slashes. Use -sto 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_profilebased 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 :amodifier.

zsh 中,您可以使用:a修饰符。

export DIRECTORY='/some//path/name//'

echo "${DIRECTORY:a}"

=> /some/path/name

This acts like realpathbut doesn't fail with missing files/directories as argument.

这就像realpath但不会因丢失文件/目录作为参数而失败。