我有一个存储在bash变量中的路径列表,例如以下
>>> MY_PATHS= ../Some/Path/ ../Some/Other/../Path/
我希望有一个独特的相对路径列表,但由于" .."在第二个路径中使用的父目录我不能将它们传递给uniq
。
是否有标准的linux方法来规范化目录路径?
我想要的结果是:
>>> echo $MY_UNIQUE_PATHS
../Some/Path/
答案 0 :(得分:2)
似乎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
。
谢谢,@ devnull!
答案 1 :(得分:0)
这是一个只有bash的版本,除了打印相对路径外,它仍然使用python的神奇relpath
函数(参见this)。
注意:路径必须存在,否则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