Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first directory components from path of file

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:

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, ...

like image 413
Libor Zapletal Avatar asked Mar 15 '11 12:03

Libor Zapletal


People also ask

How do I delete a path variable?

The way to fix it is to edit the file again and remove the duplicate paths. If you didn't edit any files, and you you must have modified the PATH interactively. In that case the changes won't "stick", ie if you open another shell, or log out and log back in, the changes will be gone automatically.


2 Answers

You can use any of:

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

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.

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

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).

like image 194
Jonathan Leffler Avatar answered Sep 23 '22 14:09

Jonathan Leffler


echo a/project/hello.c | cut -d'/' -f2- 
like image 44
Goblinhack Avatar answered Sep 22 '22 14:09

Goblinhack