使用正则表达式从 jar 中提取特定文件

使用正则表达式从 jar 中提取特定文件

我有一个配置 jar,其中的资源目录中包含如下文件。名称的格式为<text>-<text>.properties<text>-<text>-<alphanumeric>.properties

abb-servicea.properties
abb-servicea-dev1.properties
abb-serviceb-dev2.properties
abb-servicea-prod.properties
abb-serviceb.properties

我只需要从 jar 中提取以下文件

abb-servicea.properties 
abb-serviceb.properties 

我试过了unzip abb-configs.jar abb-*[a-z].properties。我无法专门选择abb-servicea.propertiesabb-serviceb.properties。它最终abb-servicea-prod.properties也显示

abb-servicea.properties
abb-serviceb.properties 
abb-servicea-prod.properties 

如何提取带有模式的文件abb-<servicename>.properties

编辑:请注意,属性名称可以是任意的abb-<anyservicename>.properties。例如:它可能是abb-serviceb.properties。所以本质上它应该将文件提取为

abb-servicea.properties 
abb-serviceb.properties 

答案1

你可以这样做:

bsdtar --exclude='*-*-*' -xf abb-configs.jar 'abb-*.properties'

提取abb-*.properties包含两个-s 的除外。

要使用正则表达式:

bsdtar -'s/^abb-[[:alpha:]]*\.properties$/~/' -'s/.*//' -xf abb-configs.jar

其中第一个-s, 对我们想要提取的存档成员进行 noop 替换(~相当于&in sed's s),第二个删除我们不想要的成员(尚未与第一个匹配),所以我们最终提取了名称与^abb-[[:alpha:]]*\.properties$正则表达式匹配的存档成员。

[[:alpha:]]*匹配 0 个或多个 alpha 的任何序列。您还可以用于[^-]*除 之外的字符序列-。替换*\{1,\}“1 或更多”而不是“0 或更多”。


在你的:

unzip abb-configs.jar abb-*[a-z].properties

首先请注意,*and[a-z]应该被引用,因为它们是 shell 通配符:

unzip abb-configs.jar 'abb-*[a-z].properties'

(这里引用整个论点)。

unzip将模式视为(基本)shell 通配符模式,而不是正则表达式。

在 shell 通配符中,*代表任意数量的字符(如.*正则表达式)。所以在这里,它匹配 onabb-servicea-prod.service因为*匹配 onservicea-pro[a-z]on d

某些 shell 具有高级通配符运算符,可以匹配一个或多个字母,例如[[:alpha:]]+扩展正则表达式的 或[[:alpha:]]\{1,\}基本正则表达式的 。这包括 ksh 的+([[:alpha:]])(也受 支持bash -O extglob)和zsh -o extendedglob[[:alpha:]]##,但这些不受 的支持unzip

您仍然可以通过执行以下操作来使用 shell 的通配符模式(此处zsh作为示例):

set -o extendedglob
members=( ${(f)"$(bsdtar tf abb-configs.jar)"} )
wanted=( ${(M)members:#abb-[[:alpha:]]##.properties} )
(( $#wanted )) && print -rNC1 -- $wanted |
  bsdtar --null -T /dev/stdin -nxf abb-configs.jar

或者进行正则表达式匹配grep(以及任何 shell):

bsdtar tf abb-configs.jar |
  grep -xE 'abb-[[:alpha:]]+\.properties' |
  tr '\n' '\0' |
  bsdtar --null -T /dev/stdin -nxf abb-configs.jar

看看这些 问题如果将这种方法用于其他模式,当前版本的bsdtarfor 会提示潜在的问题。


bsdtartar类似于库的 CLI 界面libarchive,可以操作数十种不同的存档格式,因此如果可能的话,这也是您通常想要使用的一个命令来处理存档,因为这样您就可以对所有存档格式使用相同的 API。

如果您没有并且无法安装bsdtar,但您有 Info-ZIP 的unzip命令,该命令只能处理 ZIP 文件(并且jar文件恰好是此类文件),您可以执行相同的操作(假设 GNU xargs):

xargs -rd '\n' -a <(
    unzip -Z1 abb-configs.jar |
      grep -xE 'abb-[[:alpha:]]+\.properties'
  ) unzip -q abb-configs.jar

unzip也将参数视为通配符模式,这不是问题,因为我们选择的参数不包含通配符)。

相关内容