JGeZau JGeZau - 9 months ago 51
Bash Question

Unix remove part of path

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


I want to remove the first part
and produce the output:


Note: I have several paths in a while loop, with the same
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'

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


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

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

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.