使用 bash 从给定路径中删除不必要的斜线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4638983/
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-17 23:13:19  来源:igfitidea点击:

Remove unnecessary slashes from a given path with bash

bashpath

提问by casper

How can I get rid of unnecessary slashes in a given path?

如何摆脱给定路径中不必要的斜线?

Example:

例子:

p="/foo//////bar///hello/////world"

I want:

我想要:

p="/foo/bar/hello/world"

回答by phihag

Use readlink:

使用阅读链接

p=$(readlink -m "/foo//////bar///hello/////world")

Notice that this will canonicalize symbolic links. If that's not what you want, use sed:

请注意,这将规范化符号链接。如果这不是您想要的,请使用sed

p=$(echo "/foo//////bar///hello/////world" | sed s#//*#/#g)

回答by Paused until further notice.

Using pure Bash:

使用纯 Bash:

shopt -s extglob
echo ${p//\/*(\/)/\/}

回答by Mattia72

With realpath:

使用真实路径:

realpath -sm $p

realpath -sm $p

Parameters:

参数:

  -m, --canonicalize-missing   no components of the path need exist
  -s, --strip, --no-symlinks   don't expand symlinks

回答by dsaydon

your input:

您的输入:

p="/foo//////bar///hello/////world"

command to remove the irrelevant slashes:

删除不相关斜线的命令:

echo $p | tr -s /

output:

输出:

/foo/bar/hello/world

回答by Feri

This works with multiple separators and does not assume the given path should exist:

这适用于多个分隔符,并且不假设给定的路径应该存在:

p=/foo///.//bar///foo1/bar1//foo2/./bar2; 
echo $p | awk '{while(index(,"/./")) gsub("/./","/"); while(index(,"//"))
     gsub("//","/");  print ;}'

But does not simplify well strings containing ".."

但并没有简化包含“..”的字符串

回答by Robie Basak

  1. Consider if you need to do this. On Unix, specifying duplicate path separators (and even things like /foo/.//bar///hello/./worldwork just fine.
  2. You can use readlink -f, but this will also canonicalize the symlinks in that path, so the result depends on your filesystem and the path supplied must actually exist, so this won't work for virtual paths.
  1. 考虑您是否需要这样做。在 Unix 上,指定重复的路径分隔符(甚至像这样的东西/foo/.//bar///hello/./world也很好用。
  2. 您可以使用readlink -f,但这也将使该路径中的符号链接规范化,因此结果取决于您的文件系统,并且提供的路径必须实际存在,因此这不适用于虚拟路径。

回答by casper

Thanks for the replys. I know the path works fine. I just want this for optical reasons.

感谢您的回复。我知道路径工作正常。我只是出于光学原因想要这个。

I found another solution: echo $p | replace '//' ''

我找到了另一个解决方案: echo $p | replace '//' ''