1

我想知道如何使用正则表达式来简化文件路径中的双点(路径可能实际上不存在)?

例如更改/my/path/to/.././my/./../../file.txt/my/file.txt或。path/./to/../../../file.txt../file.txt

是否可以在 bash 的一个命令中执行此操作?(sed例如,使用不是复杂的 python 或 perl 脚本)

编辑:我遇到了这个问题,但realpath在我使用的计算机上不可用。

编辑:从FJ的解决方案中,我最终构建了以下正则表达式,它适用于更一般的情况(如果路径的某些文件夹被命名,则不起作用....):

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'
4

1 回答 1

4

尝试以下操作:

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
于 2013-04-19T16:55:23.227 回答