删除 Unix 上的部分路径 [英] Remove part of path on Unix

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

问题描述

我正在尝试删除字符串中的部分路径.我有路径:

I'm trying to remove part of the path in a string. I have the path:

/path/to/file/drive/file/path/

我想删除第一部分 /path/to/file/drive 并产生输出:

I want to remove the first part /path/to/file/drive and produce the output:

file/path/

注意:我在 while 循环中有几个路径,所有路径都具有相同的 /path/to/file/drive,但我只是在寻找如何"删除所需的字符串.

Note: I have several paths in a while loop, with the same /path/to/file/drive in all of them, but I'm just looking for the 'how to' on removing the desired string.

我找到了一些示例,但我无法让它们工作:

I found some examples, but I can't get them to work:

echo /path/to/file/drive/file/path/ | sed 's:/path/to/file/drive:\2:'
echo /path/to/file/drive/file/path/ | sed 's:/path/to/file/drive:2'

\2 是字符串的第二部分,我显然做错了什么......也许有更简单的方法?

\2 being the second part of the string and I'm clearly doing something wrong...maybe there is an easier way?

推荐答案

你也可以使用 POSIX shell 变量扩展来做到这一点.

You can also use POSIX shell variable expansion to do this.

path=/path/to/file/drive/file/path/
echo ${path#/path/to/file/drive/}

#.. 部分在变量展开时去掉前导匹配字符串;如果您的字符串已经在 shell 变量中,这尤其有用,例如您正在使用 for 循环.您也可以使用 %... 从变量的末尾去除匹配的字符串(例如,扩展名).有关详细信息,请参阅 bash 手册页.

The #.. part strips off a leading matching string when the variable is expanded; this is especially useful if your strings are already in shell variables, like if you're using a for loop. You can strip matching strings (e.g., an extension) from the end of a variable also, using %.... See the bash man page for the gory details.

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

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