Replacing the parameter - delete the part of the line after the template

Let's say I have a path that looks like this:

/A/B/C/DIRECTORY/D/E/F 

Now, what I want to achieve by changing the parameters is cutting off part of the path after DIRECTORY, regardless of where the DIRECTORY path is (A, B, C, etc., just mean random directory names).

After substitution:

 /A/B/C/DIRECTORY 

This is what I have tried so far:

 #!/bin/bash if [[ $# < 1 ]] then echo "Usage: $0 DIRECTORY" fi CURRENT_DIRECTORY=$(pwd) DIRECTORY=$1 cd ${CURRENT_DIRECTORY%!(DIRECTORY)/*} 

Obviously this does not work. I could implement this using awk or sed, but I am wondering if this is possible using only parameter replacements.

+4
source share
4 answers

Maybe this will help -

 [jaypal:~/Temp] D="A/B/C/DIRECTORY/D/E/F" [jaypal:~/Temp] echo $D A/B/C/DIRECTORY/D/E/F [jaypal:~/Temp] c=${D%/*/*/*} [jaypal:~/Temp] echo $c A/B/C/DIRECTORY 
+2
source

Try the following solution:

 cd ${CURRENT_DIRECTORY/${DIRECTORY}*/""} 

EDIT:

A more accurate answer would be to add your directory after removing the last part:

 cd ${CURRENT_DIRECTORY/${DIRECTORY}*/""}$DIRECTORY 
+1
source
 [ ghoti@pc ~]$ D="/A/B/C/foo/D/E" [ ghoti@pc ~]$ echo "${D/foo*/}" /A/B/C/ 

Of course, this is not ideal:

 [ ghoti@pc ~]$ D="/A/B/C/foobar/D/foo/E" [ ghoti@pc ~]$ echo "${D/foo*/}" /A/B/C/ 

Read the bash man page and find " Template Replacement ."

+1
source

Thanks to Birei, I came to this (not an ideal but good enough solution:

 #/bin/bash if [[ $# < 1 ]] then echo "Usage: $0 BASENAME" fi echo ${PWD/%$1*/$1} 

Example:

 $ PWD=/home/ltorvalds/workspace $ ./up.sh ltorvalds /home/ltorvalds 
0
source

Source: https://habr.com/ru/post/1387100/


All Articles