【问题标题】:exporting name of last but one directory导出最后一个目录的名称
【发布时间】:2015-02-15 14:54:02
【问题描述】:

正如question 中所解释的,我们可以获得当前工作目录的名称。 但是如何获取最后一个目录名呢?

场景:

# working directory /etc/usr/abc/xyz.txt 
printf '%s\n' "${PWD##*/}" #prints abc
#i want to print usr
printf '%s\n' "%{PWD##*/-1}" #prints me whole path

建议我如何做到这一点。

提前致谢。

【问题讨论】:

  • @EtanReisner 试试echo ${PWD##*/}
  • 呸,对不起,我的假测试的工件和一个文件名的工作目录。

标签: linux bash pwd


【解决方案1】:

经典的方法是:

echo $(basename $(dirname "$PWD"))

dirname 删除路径的最后一个组件; basename 返回剩下的最后一个组件。这具有在根目录附近工作的额外优点,其中使用${PWD##…} 等进行变量编辑不一定有效。

【讨论】:

    【解决方案2】:

    假设您出于某种原因不只是想运行basename "$(dirname "$PWD")",并且您确实想为此使用扩展(注意注意事项here)。

    # Strip the current directory component off.
    tmppwd=${PWD%/*}
    # Strip all leading directory components off.
    echo "${tmppwd##*/}"
    

    但是其中一个链接的 cmets 中提到的数组扩展技巧很聪明(尽管由于其他扩展属性(如通配等)而很棘手)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 2019-11-13
      相关资源
      最近更新 更多