从在bash路径脱衣双点 [英] Strip double dots from path in bash

查看:108
本文介绍了从在bash路径脱衣双点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道它怎么会可能使用常规的前pression从文件路径(路径实际上可能不存在)?

简化双点

例如改变 /我的/路径/要/.././我/./../../ file.txt的 /my/file.txt 路径/./到/../../../ file.txt的 ../ file.txt的

是否有可能在bash做这一个命令? (使用 SED 例如,而不是一个复杂的Python或perl脚本)

修改:我碰到的这个问题的真实路径是我使用。

在电脑上无法使用

修改
FJ 的解决方案,我最终建立以下的正则表达式这在更一般的情况下工作(没有,如果一些工作文件夹道路被命名为 ...

 的sed -e的| /\\./ | / | G'-e':一个'-e的| \\ \\ ./ \\ \\ ./ |。 ./..../|g-e的|。^ [^ /] * / \\ \\ \\ / ||' -e'吨'-e的| /[^/]*/\\.\\.\\/ | / |' -e'吨'-e的| \\ \\ \\ \\ ./ |。../ | G'-e'吨'


解决方案

请尝试以下操作:

 的sed -e的| /\\./ | / | G'-e':一个'-e的| /[^/]*/\\.\\./ | / |' -e'吨'

例如:

  $回声'/my/path/to/.././my/./../../file.txt|
  SED -e的| /\\./ | / | G'-e':一个'-e的| /[^/]*/\\.\\./ | / |' -e'吨'
/my/file.txt

下面就是该方法的描述:

 在线阅读
全部替换/\\./'符合'/'
同时有/[^/]*/\\.\\./'{的比赛
    替换线/[^/]*/\\.\\./中第一次出现以/
}
输出线

I wonder how it would be possible to use a regular expression to simplify double dots from a file path (the path may not actually exist) ?

For example change /my/path/to/.././my/./../../file.txt into /my/file.txt or path/./to/../../../file.txt into ../file.txt.

Is it possible to do this in one command in bash ? (using sed for example, not a complicated python or perl script)

edit: I came across this question but realpath isn't available on the computer I use.

edit: From F.J 's solution, I ended up building the following regex which works in more general cases (does not work if some folder of the path is named ....):

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'

解决方案

Try the following:

sed -e 's|/\./|/|g' -e ':a' -e 's|/[^/]*/\.\./|/|' -e 't a'

Example:

$ echo '/my/path/to/.././my/./../../file.txt' |
  sed -e 's|/\./|/|g' -e ':a' -e 's|/[^/]*/\.\./|/|' -e 't a'
/my/file.txt

Here is a description of the approach:

read line
replace all '/\./' in line with '/'
while there is a match of '/[^/]*/\.\./' {
    replace first occurrence of '/[^/]*/\.\./' in line with '/'
}
output line

这篇关于从在bash路径脱衣双点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆