庆典:提取最后两个迪尔斯的路径 [英] bash: extracting last two dirs for a pathname

查看:101
本文介绍了庆典:提取最后两个迪尔斯的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我好像在什么pretty简单,都失败了,在bash。我有一个保存完整路径目录的字符串变量。我想最后的两个在它的目录指定到另一个字符串。举例来说,如果我有:

  DIRNAME = / A / B / C / D / E

我想:

  DIRNAME2 = D / E

我敢肯定有一个简单的bash结构或 SED 命令,将做到这一点,但它逃避我。我倒是有点像一个通用版本基本名目录名不只是返回的极端部分名称。

谢谢!
戴夫


解决方案

  DIRNAME = / A / B / C / D / E
D2 = $(目录名$ DIRNAME)
DIRNAME2 = $($基名D2)/ $(基名$ DIRNAME)

或者,在一个行:

  DIRNAME2 = $($基名(目录名称$ DIRNAME))/ $(基名$ DIRNAME)

除非你大举进入受虐狂不要尝试游戏的反引号。如果有可能的空间在路径用双引号周围的变量名。

这将与几乎所有的壳工作(甚至是第7版的Unix Bourne shell的 - 如果你使用反引号毕竟的受虐狂放纵)。在庆典,也有其他机制可用 - 其他的答案说明一些许多选择,但 EXPR 也是一个老-school溶液(它是在第7版的Unix太present)。

  DIRNAME2 =`基名\\`目录名称$ DIRNAME\\``/`基名$ DIRNAME`

(两个嵌套层次是不是太可怕了;!3得到棘手)

I seem to have failed at something pretty simple, in bash. I have a string variable that holds the full path to a directory. I'd like to assign the last two directories in it to another string. For example, if I have:

DIRNAME = /a/b/c/d/e

I'd like:

DIRNAME2 = d/e

I'm sure there's a simple bash construct or sed command that will do it, but it's escaping me. I'd sort of like a generalized version of basename or dirname that doesn't just return the extreme parts of a name.

Thanks! Dave

解决方案

DIRNAME=/a/b/c/d/e
D2=$(dirname $DIRNAME)
DIRNAME2=$(basename $D2)/$(basename $DIRNAME)

Or, in one line:

DIRNAME2=$(basename $(dirname $DIRNAME))/$(basename $DIRNAME)

Don't try that game with back-quotes unless you're heavily into masochism. And if there might be spaces in the paths, use double quotes around the variable name.

This will work with almost any shell (even a 7th Edition Unix Bourne shell - if you indulge in the masochism of using back-quotes after all). In bash, there are other mechanisms available - other answers illustrate some of the many options, though expr is also an old-school solution (it was present in 7th Edition Unix too).

DIRNAME2=`basename \`dirname "$DIRNAME"\``/`basename "$DIRNAME"`

(Two levels of nesting is not too awful; three gets tricky!)

这篇关于庆典:提取最后两个迪尔斯的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆