Bash 在匹配组上查找/替换和运行命令

标签 bash awk sed

我正在尝试执行动态查找/替换,其中查找到的匹配组在替换中被操纵。

测试文件:

…
other text
base64_encode_SOMEPATH_ something
other(stuff)
text base64_encode_SOMEOTHERPATH_
…

像这样:

sed -i "" -e "s/(base64_encode_(.*)_)/cat MATCH | base64/g" testfile

这会输出类似的东西:

…
other text
U09NRVNUUklORwo= something
other(stuff)
text U09NRU9USEVSU1RSSU5HCg==
…

最佳答案

根据您的新要求进行了更新。为方便起见,现在使用 GNU awk 作为第三个参数来 match() :

$ awk 'match($0,/(.*)base64_encode_([^_]+)_(.*)/,arr) {
      cmd = "base64 <<<" arr[2]
      if ( (cmd | getline rslt) > 0) {
          $0 = arr[1] rslt arr[3]
      }
      close(cmd)
  } 1' file
…
other text
U09NRVNUUklORwo= something
other(stuff)
text U09NRU9USEVSU1RSSU5HCg==
…

确保您阅读并理解http://awk.info/?tip/getline如果您要使用 getline

如果你不能安装 GNU awk(但你真的,真的会从中受益所以一定要试试)那么像这样的东西可以与任何现代 awk 一起工作:

$ awk 'match($0,/base64_encode_[^_]+_/) {
      arr[1] = substr($0,1,RSTART-1)
      arr[2] = arr[3] = substr($0,RSTART+length("base64_encode_"))
      sub(/_.*$/,"",arr[2])
      sub(/^[^_]+_/,"",arr[3])

      cmd = "base64 <<<" arr[2]
      if ( (cmd | getline rslt) > 0) {
          $0 = arr[1] rslt arr[3]
      }
      close(cmd)
  } 1' file

我说“类似”是因为您可能需要调整 substr() 和/或 sub() args 如果它们稍微偏离,我还没有测试过。

关于Bash 在匹配组上查找/替换和运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27390782/

相关文章:

c++ - 用于编译和运行 C++ 的 bash 脚本

linux - 使用awk在top命令中进行字段分隔

regex - 使用 sed 删除 html 注释标签

awk - 如何围绕每个部分的一个特定字母将数据拆分为 5 个字母

linux - 如何在 Linux 上使用 exec 选项转义传递给 find 的命令

bash - 在heredoc中禁用命令替换?

Bash - 从 Bash Var 或 AZ 命令设置 Azure 变量

linux - 使用 awk 命令用逗号替换双引号 csv 文件中的管道

awk - 当节的内容与模式匹配时打印文件的节

awk - 使用 sed 删除特定列的小数