2

我正在尝试在 Bash 中编写 dirname 函数,以便它不使用任何外部命令。

function dirname() {
  local path=$1
  [[ $path =~ ^[^/]+$ ]] && dir=. || {              # if path has no slashes, set dir to .
    [[ $path =~ ^/+$ ]]  && dir=/ || {              # if path has only slashes, set dir to /
      local IFS=/ dir_a i
      read -ra dir_a <<< "$path"                    # read the components of path into an array
      dir="${dir_a[0]}"
      for ((i=1; i < ${#dir_a[@]}; i++)); do        # strip out any repeating slashes
        [[ ${dir_a[i]} ]] && dir="$dir/${dir_a[i]}" # append unless it is an empty element
      done
    }
  }

  [[ $dir ]] && printf '%s\n' "$dir"                # print only if not empty
}

为了/从路径中删除任何重复,我不得不使用数组逻辑。有没有更简单的方法来做同样的Bash 参数扩展?我试过了,但我似乎没有做对。

基本上,我想用一个斜杠替换所有出现的多个连续斜杠。

4

1 回答 1

4

如果extglob开启:

shopt -s extglob

你可以这样做:

printf '%s\n' "${path//\/+(\/)/\/}"

这使用${var//pattern/replacement}语法进行全局替换。

模式是\/+(\/)(带有转义的斜杠,因为/是分隔符),实际上是/+(/)+(/)意思是“一个或多个斜杠”)。

于 2017-10-18T05:29:35.563 回答