I have the path /home/bamboo/bamboo-agent-home/xml-data/build-dir/NG-VOSGQL239-JOB1
and would like to get just /home/bamboo/bamboo-agent-home/xml-data/build-dir/
How can I delete the last part of the path if it can be with different lengths by using Bash?
答案 0 :(得分:3)
Some common ways to do that are:
$ str=/home/bamboo/bamboo-agent-home/xml-data/build-dir/NG-VOSGQL239-JOB1
$ echo "${str%/*}" # fast, but wrong if str has no "/"s in it
/home/bamboo/bamboo-agent-home/xml-data/build-dir
$ dirname "$str" # slow, but returns "." for bare names
/home/bamboo/bamboo-agent-home/xml-data/build-dir
$ echo "$str" | sed 's@/[^/]*$@@' # more general, but slow *and* wrong with no "/"s
/home/bamboo/bamboo-agent-home/xml-data/build-dir
Note, in the above, we use "wrong" to indicate unexpected behavior in the case of path manipulation. (eg, we define the output of dirname
to be the correct behavior.)
答案 1 :(得分:2)
Use dirname
dirname /home/bamboo/bamboo-agent-home/xml-data/build-dir/NG-VOSGQL239-JOB
答案 2 :(得分:2)
Using bash regex =~
:
$ var=/home/bamboo/bamboo-agent-home/xml-data/build-dir/NG-VOSGQL239-JOB
$ [[ $var =~ .*/ ]] && echo "${BASH_REMATCH[0]}"
/home/bamboo/bamboo-agent-home/xml-data/build-dir/