简体   繁体   中英

Remove part of a string by using bash

我的路径为/home/bamboo/bamboo-agent-home/xml-data/build-dir/NG-VOSGQL239-JOB1 ,想获取/home/bamboo/bamboo-agent-home/xml-data/build-dir/如果使用Bash可以将路径的最后部分设置为不同的长度,如何删除路径的最后一部分?

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

使用目录名

dirname /home/bamboo/bamboo-agent-home/xml-data/build-dir/NG-VOSGQL239-JOB

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM