击:自变量删除一个目录组件(文件的路径) [英] Bash: remove first directory component from variable (path of file)

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

问题描述

我需要从Bash中的变量删除一个目录(最左边)。我找到了我怎么能去除所有的路径,或使用目录名和其他人,但它移除所有或右边一条路径组成部分;它不会帮助我。所以,你有一个更好的理解我需要什么,我会写一个例子:

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 /项目/ hello.c的 A /项目/文档/ README ,...我想删除 A / 这样一些命令后I'll有项目/ hello.c的项目/文档/ 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, ...

推荐答案

您可以使用任何的:

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

这三个回声命令产生 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.

当您有包含您需要删除preFIX(轻微变种变量二是适当的: Y = A;回声$ {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/}).

第三个是最普遍的 - 它删除任意preFIX到第一个斜线。我惊喜地发现, * 工作非贪婪时我测试了庆典(版本3.2)上MacOS X的10.6.6 - 我把下来太多Perl和正则表达式的工作(因为,当我仔细想想, * 壳不包括斜杠)

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天全站免登陆