从部分已知目录中提取子目录路径

Dar*_*olt 5 bash find string search regular-expression

假设我有以下目录结构:

base/
|
+-- app
|   |
|   +-- main
|       |
|       +-- sub
|           |
|           +-- first
|           |   |
|           |   +-- tib1.ear
|           |   \-- tib1.xml
|           |
|           \-- second
|               |
|               +-- tib2.ear
|               \-- tib2.xml
Run Code Online (Sandbox Code Playgroud)

ear文件的相对路径之一是base/app/main/sub/first/tib1.ear,我如何提取子字符串:

  • 文件,tib1.eartib2.ear
  • base/app/但不包括文件的子目录,即main/sub/firstmain/sub/second

所有的目录名称都是动态生成的,所以我不知道它们之外base/app/,因此不能简单地使用已知子字符串的长度并cut用来截断它们;但是我知道一旦知道文件名是怎么可能的。我只是觉得有一种比根据其他结果的长度切割和连接一堆字符串更简单的方法。

我记得看到过一些类似于此的正则表达式魔术。它处理用反斜杠拆分和连接子字符串,但遗憾的是,我不记得他们是怎么做的,也不记得我在哪里看到它再次查找它。

Joh*_*024 7

让我们从您的文件名开始:

$ f=base/app/main/sub/first/tib1.ear
Run Code Online (Sandbox Code Playgroud)

提取基本名称:

$ echo "${f##*/}"
tib1.ear
Run Code Online (Sandbox Code Playgroud)

要提取目录名称的所需部分:

$ g=${f%/*}; echo "${g#base/app/}"
main/sub/first
Run Code Online (Sandbox Code Playgroud)

${g#base/app/}${f##*/}去除前缀的例子。 ${f%/*}是一个去除后缀的例子。

文档

来自man bash

   ${parameter#word}
   ${parameter##word}
          Remove  matching prefix pattern.  The word is expanded to produce a pattern just as in pathname expansion.  If
          the pattern matches the beginning of the value of parameter, then the result of the expansion is the  expanded
          value  of  parameter  with the shortest matching pattern (the ``#'' case) or the longest matching pattern (the
          ``##'' case) deleted.  If parameter is @ or *, the pattern removal operation is  applied  to  each  positional
          parameter  in  turn,  and  the expansion is the resultant list.  If parameter is an array variable subscripted
          with @ or *, the pattern removal operation is applied to each member of the array in turn, and  the  expansion
          is the resultant list.

   ${parameter%word}
   ${parameter%%word}
          Remove  matching suffix pattern.  The word is expanded to produce a pattern just as in pathname expansion.  If
          the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is
          the  expanded  value  of parameter with the shortest matching pattern (the ``%'' case) or the longest matching
          pattern (the ``%%'' case) deleted.  If parameter is @ or *, the pattern removal operation is applied  to  each
          positional parameter in turn, and the expansion is the resultant list.  If parameter is an array variable sub?
          scripted with @ or *, the pattern removal operation is applied to each member of the array in  turn,  and  the
          expansion is the resultant list.
Run Code Online (Sandbox Code Playgroud)

备择方案

您可能还需要考虑实用程序basenamedirname

$ basename "$f"
tib1.ear
$ dirname "$f"
base/app/main/sub/first
Run Code Online (Sandbox Code Playgroud)