Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

shell - Remove part of path on Unix

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

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

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

file/path/

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 being the second part of the string and I'm clearly doing something wrong...maybe there is an easier way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you wanted to remove a certain NUMBER of path components, you should use cut with -d'/'. For example, if path=/home/dude/some/deepish/dir:

To remove the first two components:

# (Add 2 to the number of components to remove to get the value to pass to -f)
$ echo $path | cut -d'/' -f4-
some/deepish/dir

To keep the first two components:

$ echo $path | cut -d'/' -f-3
/home/dude

To remove the last two components (rev reverses the string):

$ echo $path | rev | cut -d'/' -f4- | rev
/home/dude/some

To keep the last three components:

$ echo $path | rev | cut -d'/' -f-3 | rev
some/deepish/dir

Or, if you want to remove everything before a particular component, sed would work:

$ echo $path | sed 's/.*(some)/1/g'
some/deepish/dir

Or after a particular component:

$ echo $path | sed 's/(dude).*/1/g'
/home/dude

It's even easier if you don't want to keep the component you're specifying:

$ echo $path | sed 's/some.*//g'
/home/dude/

And if you want to be consistent you can match the trailing slash too:

$ echo $path | sed 's//some.*//g'
/home/dude

Of course, if you're matching several slashes, you should switch the sed delimiter:

$ echo $path | sed 's!/some.*!!g'
/home/dude

Note that these examples all use absolute paths, you'll have to play around to make them work with relative paths.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...