在bash脚本中使用中间的父“..”目录规范化路径

时间:2014-03-12 06:28:51

标签: python linux bash path

我有一个存储在bash变量中的路径列表,例如以下

>>> MY_PATHS= ../Some/Path/ ../Some/Other/../Path/

我希望有一个独特的相对路径列表,但由于" .."在第二个路径中使用的父目录我不能将它们传递给uniq

是否有标准的linux方法来规范化目录路径?

我想要的结果是:

>>> echo $MY_UNIQUE_PATHS
../Some/Path/

2 个答案:

答案 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