在最后一个“/”之前返回所有内容

时间:2015-11-02 23:09:01

标签: regex bash

我想要一个能够执行以下操作的正则表达式:

  1. 给定一个目录,返回上一个目录。所以,基本上删除最后一个“/”以及之后的所有内容。你可以假设字符串不会以“/ something /”结尾,而是“/ something”。
  2. 示例:

      • 鉴于:“ / home / development
      • 返回:“ / home
      • 鉴于:“ / home / simulations / database
      • 返回:“ / home / simulations
      • 鉴于:“ / home / simulations / workingConfig / system / customer
      • 返回:“ / home / simulations / workingConfig / system
  3. 我一直在使用像/[^/]*$这样的正则表达式和类似的命令

    expr match "/home/simulations/database" '\(/[^/]*$\)'

    没有运气。有什么帮助吗?

3 个答案:

答案 0 :(得分:3)

使用诸如sed之类的外部命令是不必要的低效率; bash可以使用try-with-resources Statement内置这个内容:

s=${s%/*}

这会在字符串末尾为/*执行非贪婪的parameter expansion并删除它找到的所有内容。因此:

$ s=/home/simulations/database
$ echo "${s%/*}"
/home/simulations

另见pattern match

那就是说,如果真的想要使用正则表达式,bash也可以只使用内置功能来实现:

$ s=/home/simulations/database
$ [[ $s =~ ^(.*)/[^/]*$ ]] && s=${BASH_REMATCH[1]}
$ echo "$s"
/home/simulations

答案 1 :(得分:3)

您正在寻找dirname

$ dirname /home/development /home/simulations/database /home/simulations/workingConfig/system/customer
/home
/home/simulations
/home/simulations/workingConfig/system

答案 2 :(得分:1)

您可能希望使用sed,因为它非常直接:

sed 's@/[^/]*$@@' <<< "string"

这会删除上一个/

中的所有内容

测试

$ cat a
/home/simulations/workingConfig/system/customer
/home/simulations/database
/home/development

$ sed 's@/[^/]*$@@' a
/home/simulations/workingConfig/system
/home/simulations
/home