用父".."规范化路径bash脚本中间的目录 [英] Normalize paths with parent ".." directories in the middle in bash script
本文介绍了用父".."规范化路径bash脚本中间的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个存储在bash变量中的路径列表,例如以下内容
I have a list of paths stored in a bash variable, such as the following
>>> MY_PATHS= ../Some/Path/ ../Some/Other/../Path/
我想要一个唯一的相对路径列表,但是由于第二个路径中使用了".."父目录,所以我不能仅将它们通过管道传递给 uniq
.
I'd like to have a list of unique relative paths, but due to the ".." parent directory used in the second path I can't just pipe these to uniq
.
是否存在标准化目录路径的标准Linux方法?
我想要的结果是这样
>>> echo $MY_UNIQUE_PATHS
../Some/Path/
推荐答案
It seems python's relpath
can do it all for me...
#!/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
替换为 绝对路径
.
If absolute paths are wanted, replace relpath
with abspath
.
谢谢@devnull!
Thanks, @devnull!
这篇关于用父".."规范化路径bash脚本中间的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文