Remove unnecessary slashes from a given path with bash

前端 未结 8 1816
囚心锁ツ
囚心锁ツ 2021-02-05 15:04

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

Example:

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

I want:

p=\"/f         


        
相关标签:
8条回答
  • 2021-02-05 15:12
    1. Consider if you need to do this. On Unix, specifying duplicate path separators (and even things like /foo/.//bar///hello/./world work 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.
    0 讨论(0)
  • 2021-02-05 15:14

    With realpath:

    realpath -sm $p

    Parameters:

      -m, --canonicalize-missing   no components of the path need exist
      -s, --strip, --no-symlinks   don't expand symlinks
    
    0 讨论(0)
  • 2021-02-05 15:15

    In zsh:

    echo "${p:a}"
    

    Works with non-existent paths, too.

    0 讨论(0)
  • 2021-02-05 15:20

    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($1,"/./")) gsub("/./","/"); while(index($1,"//"))
         gsub("//","/");  print $1;}'
    

    But does not simplify well strings containing ".."

    0 讨论(0)
  • 2021-02-05 15:21

    Using pure Bash:

    shopt -s extglob
    echo ${p//\/*(\/)/\/}
    
    0 讨论(0)
  • 2021-02-05 15:27

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

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

    0 讨论(0)
提交回复
热议问题