从文件路径中删除第一个目录组件 [英] Remove first directory components from path of file

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

问题描述

我需要从Bash中的变量中删除一个目录(最左侧).我找到了删除所有路径或使用dirname以及其他路径的方法,但是它删除了右侧的全部或一个路径组件.这对我没有帮助.因此,您对我的需求有了更好的了解,我将写一个示例:

I need to remove one directory (the leftmost) from variables in Bash. I found ways how can I remove all the path or use dirname and others but it was removing all or one path component on the right side; it wouldn't help me. So you have a better understanding of what I need, I'll write an example:

我有a/project/hello.ca/project/docs/README,...,我想删除该a/,所以在执行某些命令后,我将拥有project/hello.cproject/docs/README,...

I have a/project/hello.c, a/project/docs/README, ... and I want to remove that a/ so after some commands I´ll have project/hello.c and project/docs/README, ...

推荐答案

您可以使用以下任何一种方式:

You can use any of:

x=a/b/c/d
y=a/
echo ${x#a/}
echo ${x#$y}
echo ${x#*/}

所有三个echo命令都产生b/c/d;您当然可以选择任何方式使用该值.

All three echo commands produce b/c/d; you could use the value in any way you choose, of course.

当您知道编写脚本时需要删除的名称时,第一个是合适的.

The first is appropriate when you know the name you need to remove when writing the script.

当您的变量包含需要删除的前缀(较小的变体:y=a; echo ${x#$y/})时,第二个是合适的.

The second is appropriate when you have a variable that contains the prefix you need to remove (minor variant: y=a; echo ${x#$y/}).

第三个是最通用的-它删除直到第一个斜杠的所有任意前缀.当我在MacOS X 10.6.6上用bash(3.2版)对其进行测试时,发现*不能令人满意地工作时,我感到很惊讶-我将它归结为过多的Perl和正则表达式工作(因为,当我考虑它时,shell中的*不包含斜杠).

The third is the most general - it removes any arbitrary prefix up to the first slash. I was pleasantly surprised to find that the * worked non-greedily when I tested it with bash (version 3.2) on MacOS X 10.6.6 - I'll put that down to too much Perl and regex work (because, when I think about it, * in shell doesn't include slashes).

这篇关于从文件路径中删除第一个目录组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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