我想知道如何使用正则表达式来简化文件路径中的双点(路径可能实际上不存在)?
例如,将/my/path/to/.././my/./../../file.txt
更改为/my/file.txt
或path/./to/../../../file.txt
更改为../file.txt
。
是否可以在bash中的一个命令中执行此操作? (例如,使用sed
,而不是复杂的python或perl脚本)
修改:我遇到了this question,但我使用的计算机上找不到realpath
。
修改:
从F.J的解决方案开始,我最终构建了以下正则表达式,它适用于更一般的情况(如果路径的某个文件夹名为....
,则不起作用):
sed -e 's|/\./|/|g' -e ':a' -e 's|\.\./\.\./|../..../|g' -e 's|^[^/]*/\.\.\/||' -e 't a' -e 's|/[^/]*/\.\.\/|/|' -e 't a' -e 's|\.\.\.\./|../|g' -e 't a'
答案 0 :(得分:3)
尝试以下方法:
sed -e 's|/\./|/|g' -e ':a' -e 's|/[^/]*/\.\./|/|' -e 't a'
示例:
$ echo '/my/path/to/.././my/./../../file.txt' |
sed -e 's|/\./|/|g' -e ':a' -e 's|/[^/]*/\.\./|/|' -e 't a'
/my/file.txt
以下是该方法的说明:
read line
replace all '/\./' in line with '/'
while there is a match of '/[^/]*/\.\./' {
replace first occurrence of '/[^/]*/\.\./' in line with '/'
}
output line