【问题标题】:best way to find top-level directory for path in bash [duplicate]在bash中查找路径的顶级目录的最佳方法[重复]
【发布时间】:2019-05-26 12:59:30
【问题描述】:

我需要一个命令,它将返回 bash 中指定路径的顶级基本目录。

我有一个可行的方法,但看起来很丑:

echo "/go/src/github.myco.com/viper-ace/psn-router" | cut -d "/" -f 2 | xargs printf "/%s"

似乎有更好的方法,但是我见过的所有替代方法似乎都更糟。

感谢您的任何建议!

【问题讨论】:

  • 我更新为前缀为“/”
  • 对于cut,您可以使用-f-2
  • 是的,在这种情况下,基本目录可能是一个更好的术语。更新

标签: bash


【解决方案1】:

一个选项是使用awk

echo "/go/src/github.myco.com/viper-ace/psn-router" |
awk -F/ '{print FS $2}'

/go

【讨论】:

  • 谢谢,我认为这既简短又易读。绝对比我的解决方案好
【解决方案2】:

这是一个 sed 的可能性。还是丑。处理像////////home/path/to/dir 这样的事情。换行符仍然爆炸。

$ echo "////home/path/to/dir" | sed 's!/*\([^/]*\).*!\1!g'
/home

换行符打破它:

$ cd 'testing '$'\n''this' 
$ pwd
/home/path/testing
this
$ pwd | sed 's!/*\([^/]*\).*!/\1!g'
/home
/this

如果您知道您的目录通常会被命名,那么您和 anubhava 的解决方案肯定看起来更具可读性。

【讨论】:

    【解决方案3】:

    不确定更好,但sed

    $ echo "/go/src/github.myco.com/viper-ace/psn-router" | sed -E 's_(/[^/]+).*_\1_'
    /go
    

    【讨论】:

      【解决方案4】:

      这是一个函数中的 bash、sed 和 tr:

      #!/bin/bash
      
      
      
      
      function topdir(){
        dir=$( echo "$1" | tr '\n' '_' )
        echo "$dir" | sed -e 's#^\(/[^/]*\)\(.*\)$#\1#g'
      }
      
      
      
      topdir '/go/src/github.com/somedude/someapp'
      
      topdir '/home/somedude'
      
      topdir '/with spaces/more here/app.js'
      
      topdir '/with newline'$'\n''before/somedir/somefile.txt'
      

      问候!

      【讨论】:

      • 你是对的。编辑
      【解决方案5】:

      作为一种本机 bash 方法,不分叉子外壳,也不调用其他程序(因此,编写以最大限度地减少开销),它在极端情况下正常工作包括带有换行符的目录:

      topdir() {
          local re='^(/+[^/]+)'
          [[ $1 =~ $re ]] && printf '%s\n' "${BASH_REMATCH[1]}"
      }
      

      与此处的大多数其他解决方案一样,调用将类似于 outvar=$(topdir "$path")


      为了进一步减少开销,您可以传入目标变量名称而不是捕获标准输出:

      topdir() {
          local re='^(/+[^/]+)'
          [[ $1 =~ $re ]] && printf -v "$2" '%s' "${BASH_REMATCH[1]}"
      }
      

      ...用作:topdir "$path" outvar,之后"$outvar" 将扩展为结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-21
        • 2019-06-14
        • 1970-01-01
        • 2015-08-06
        • 1970-01-01
        • 1970-01-01
        • 2020-05-07
        • 2016-12-12
        相关资源
        最近更新 更多