【问题标题】:bash display parts of a variable that contains a pathbash 显示包含路径的变量的部分内容
【发布时间】:2016-02-26 18:42:30
【问题描述】:

我正在尝试输出文件路径的部分内容,但删除了文件名和路径的某些级别。

目前我有一个 for 循环做很多事情,但我正在从完整的文件路径创建一个变量,并想去掉一些位。

例如

for f in (find /path/to/my/file - name *.ext)

给我

$f = /path/to/my/file/filename.ext

我想做的是 printf/echo 一些变量。我知道我能做到:

printf ${f#/path/to/}
my/file/filename.ext

但我想删除文件名并最终得到:

my/file

有什么简单的方法可以做到这一点而不必使用 sed/awk 等?

【问题讨论】:

  • 尝试${f%/*} 仅删除文件名(类似于dirname 内置)。 (您应该确保在删除之前有超过 1 个 / 或在之后检查零长度)

标签: bash awk sed


【解决方案1】:

当你知道你想要的路径级别时,你可以使用 cut:

echo "/path/to/my/filename/filename.ext" | cut -d/ -f4-5

当你想要路径的最后两层时,可以使用sed

echo "/path/to/my/file/filename.ext" | sed 's#.*/\([^/]*/[^/]*\)/[^/]*$#\1#'

解释:

s/from/to/ and s#from#to# are equivalent, but will help when from or to has slashes.
s/xx\(remember_me\)yy/\1/ will replace "xxremember_meyy" by "remember_me"
s/\(r1\) and \(r2\)/==\2==\1==/ will replace "r1 and r2" by "==r2==r1=="
.* is the longest match with any characters
[^/]* is the longest match without a slash
$ is end of the string for a complete match

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2020-01-10
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多