[英]Normalize paths with parent “..” directories in the middle in bash script
我有一個存儲在bash變量中的路徑列表,如下所示
>>> MY_PATHS= ../Some/Path/ ../Some/Other/../Path/
我想要一個唯一的相對路徑列表,但由於第二個路徑中使用的“..”父目錄,我不能只將它們傳遞給uniq
。
是否有標准的linux方法來規范化目錄路徑?
我想要的結果是這樣的:
>>> echo $MY_UNIQUE_PATHS
../Some/Path/
似乎python的relpath
可以為我做這一切......
#!/usr/bin/python
import sys, os, pipes
paths = sys.argv[1:] #arguments are a list of paths
paths = map(os.path.relpath, paths) #"normalize" and convert to a relative path
paths = set(paths) #remove duplicates
paths = map(pipes.quote, paths) #for filenames with spaces etc
print " ".join(paths) #print result
例子:
>>> normpath ../Some/Path/ ../Some/Other/../Path/
../Some/Path
>>> normpath ../Some/Path/ ../Some/Other/../Different\ Path/
'../Some/Different Path' ../Some/Path
如果需要絕對路徑, relpath
用abspath
替換abspath
。
謝謝,@ devnull!
這是一個只在bash中的版本,除了打印相對路徑之外,它仍然使用python的神奇relpath
函數(參見本文 )。
注意:路徑必須存在,否則realpath
失敗:(
#!/usr/bin/bash
IFS=$'\r\n' #so the arrays abspaths and relpaths are created with just newlines
#expand to absolute paths and remove duplicates
abspaths=($(for p in "$@"; do realpath "$p"; done | sort | uniq))
printf "%q " "${abspaths[@]}" #use printf to escape spaces etc
echo #newline after the above printf
#use python to get relative paths
relpath(){ python -c "import os.path; print os.path.relpath('$1','${2:-$PWD}')" ; }
relpaths=($(for p in "${abspaths[@]}"; do relpath "$p"; done))
printf "%q " "${relpaths[@]}"
echo
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.