我有一个存储在bash变量中的路径列表,如
>>> MY_PATHS= ../Some/Path/ ../Some/Other/../Path/我想要一个唯一相对路径的列表,但是由于"..“在第二条路径中使用的父目录--我不能只是将这些管道输送到uniq。
是否有一种标准的linux方法来规范目录路径?
我想要的结果是:
>>> echo $MY_UNIQUE_PATHS
../Some/Path/发布于 2014-03-12 07:09:06
似乎蟒蛇的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!
发布于 2014-03-12 12:05:22
这里有一个仅在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[@]}"
echohttps://stackoverflow.com/questions/22343637
复制相似问题