首页 > 解决方案 > 使用 Bash 从 Cargo.toml 中提取 bin 名称

问题描述

我正在尝试使用 Bash 从 Cargo.toml 中提取 bin 名称,我启用了这样的 perl 正则表达式

第一次尝试

grep -Pzo '(?<=(^\[\[bin\]\]))\s*name\s*=\s*"(.*)"' ./Cargo.toml

正则表达式在regex101 在此处输入图像描述测试 但一无所获

Pzo选项用法可以在这里找到

第二次尝试

grep -P (?<=(^[[bin]]))\n*\s名称\s =\s*"(.*)" ./Cargo.toml

依然没有

grep -Pzo '(?<=(^\[\[bin\]\]))\s*name\s*=\s*"(.*)"' ./Cargo.toml

货运.toml

[[bin]]
name = "acme1"
path = "bin/acme1.rs"

[[bin]]
name = "acme2"
path = "src/acme1.rs"

标签: greptoml

解决方案


使用您展示的示例和尝试,请尝试使用tac+awk组合的以下代码,这将更易于维护,并且可以轻松完成工作,这在grep.

tac Input_file | 
awk '
  /^name =/{
    gsub(/"/,"",$NF)
    value=$NF
    next
  }
  /^path[[:space:]]+=[[:space:]]+"bin\//{
    print value
    value=""
  }
' | 
tac

说明:为上述代码添加详细说明。

tac Input_file |                             ##Using tac command on Input_file to print it in bottom to top order.
awk '                                        ##passing tac output to awk as standard input.
  /^name =/{                                 ##Checking if line starts from name = then do following.
    gsub(/"/,"",$NF)                         ##Globally substituting " with NULL in last field.
    value=$NF                                ##Setting value to last field value here.
    next                                     ##next will skip all further statements from here.
  }
  /^path[[:space:]]+=[[:space:]]+"bin\//{    ##Checking if line starts from path followed by space = followed by spaces followed by "bin/ here.
    print value                              ##printing value here.
    value=""                                 ##Nullifying value here.
  }
' |                                          ##Passing awk program output as input to tac here. 
tac                                          ##Printing values in their actual order.

推荐阅读