从Unix树中删除路径前缀 [英] Remove path prefix from unix tree

查看:63
本文介绍了从Unix树中删除路径前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在UNIX命令
中有一个要求,我在其中具有类似于以下的路径:

I have a requirements in UNIX command where i have a path similar to this:

path/to/file/manyfiles.extensions

现在我想要的输出类似于-

now i want the output something similar to-

file/manyfiles.extensions

现在我可以列出/ path / to和/ path了,将它们一一删除。

now i can do this listing both /path/to and /path removing them one by one.

但是我可能只会得到 / path / to输入,我必须用一个命令从树中删除这两个文件。

but i might get only "/path/to" as my input and i have to remove both from the tree in one command.

您可能认为我可以列出要删除的2个文件夹,但是在许多情况下,我得到的结构具有在许多情况下,我只需要第一个和最后一个文件夹的子文件夹中的12-13。

You might think that i can list 2 folders to remove, but in many a cases i get structures having 12-13 of subfolders in which i need only the first and last folder in many cases.

例如-`源文件-target / classes /

eg - `Source files - target/classes/

删除前缀-目标`

结果:

classes/my/code/HelloWorld.class
classes/my/code/HelloWorldImpl.class
classes/my/code/Main.class


推荐答案

如果我正确理解了您的问题,则希望在路径上去除某些给定的前缀。给定一个声明 path = / a / path / to / a / directory 和一个模式 * a / ,您可以删除在Bash中以两种方式关闭与该模式匹配的前缀:

If I understand your question correctly, you want to strip off some given prefix on a path. Given a declaration path=/a/path/to/a/directory and a pattern *a/ you can strip off the prefix matching that pattern in two ways in Bash:

echo ${path#*a/}    # outputs "path/to/a/directory"
echo ${path##*a/}   # outputs "directory"

第一个变量为非贪婪,在第一个匹配项处停止,而第二个变量为贪婪,并在该模式的最长匹配项处停止。模式 * a / 在此处出现两次,因此结果不同。

The first variant is non-greedy and stops at the first match, while the second is greedy and stops at the longest possible match for the pattern. The pattern *a/ occurs twice in out path here, so the results are then different.

模式将类似于 path / to 和路径 path / to / file / manyfiles.extensions 以下内容将起作用,具体取决于您是否需要贪婪:

In your case the pattern would be something like path/to and the path path/to/file/manyfiles.extensions, so one of the following would work, depending on whether you need to be greedy or not:

path=path/to/file/manyfiles.extensions
path=${path#*path/to/}   # assigns "file/manyfiles.extensions" to $path

path=path/to/file/manyfiles.extensions
path=${path##*path/to/}  # assigns "file/manyfiles.extensions" to $path

作为参考,请阅读 Bash参数扩展

这篇关于从Unix树中删除路径前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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