Skip to content
Advertisement

Bash: Cut current path until a certain folder

lets say I have three bash files in different directories:

/a/b/c/d/e/f/script1.sh
/a/bb/c/d/script2.sh
/aa/b/c/d/e/f/g/h/script3.sh

If I call $(pwd) I get the path of the current directory. Is there a way to somehow “crop” this path until a certain folder? In the following an example is shown if the certain folder would be called “c”:

  • In the case of script1.sh I would like to have the path: /a/b/c
  • In the case of script2.sh I would like to have the path: /a/bb/c
  • In the case of script3.sh I would like to have the path: /aa/b/c

Thank you for your help

Advertisement

Answer

I assume what you want is parameter expansion :

$ path="/a/b/c/d/e/f/script1.sh"
$ echo "${path#*/c}"
/d/e/f/script1.sh

Edit

Inversed :

$ path="/a/b/c/d/e/f/script1.sh"
$ echo "${path%/d*}"
/a/b/c

Regards!

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement