Bash

從部分已知目錄中提取子目錄路徑

  • May 3, 2019

可以說我有以下目錄結構:

base/
|
+-- app
|   |
|   +-- main
|       |
|       +-- sub
|           |
|           +-- first
|           |   |
|           |   +-- tib1.ear
|           |   \-- tib1.xml
|           |
|           \-- second
|               |
|               +-- tib2.ear
|               \-- tib2.xml

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

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

所有的目錄名稱都是動態生成的,所以我不知道它們base/app/,因此不能簡單地使用已知子字元串的長度cut來截斷它們;但是我知道一旦知道文件名,這怎麼可能。我只是覺得有一種比根據其他結果的長度切割和連接一堆字元串更簡單的方法。

我記得看到一些類似於此的正則表達式魔術。它處理使用反斜杠拆分和連接子字元串,但遺憾的是,我不記得他們是如何做到的,也不記得我在哪裡看到它再次查找它。

讓我們從您的文件名開始:

$ f=base/app/main/sub/first/tib1.ear

要提取基本名稱:

$ echo "${f##*/}"
tib1.ear

要提取目錄名稱的所需部分:

$ g=${f%/*}; echo "${g#base/app/}"
main/sub/first

${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.

備擇方案

您可能還需要考慮實用程序basenamedirname

$ basename "$f"
tib1.ear
$ dirname "$f"
base/app/main/sub/first

引用自:https://unix.stackexchange.com/questions/392528