regex - 下一个单词的 GREP 跟随包含变量的字符串

我在 bash 变量中有这个字符串

name : br-ext protocols : [protocol] name : br-ex protocols : [] name : br-local protocols : [other protocol] name : br-int protocols : []

和一个包含名称的变量 $br :值(即 br-ext)

给定 $br,我想访问它后面的协议(protocol)字符串(因此 $br br-ext 应该得到 'protocol' 而 $br-ex 应该得到 '')

我已经试过了,但它似乎没有访问变量的值

echo $protocols | grep -oP "(?<=\"$br\")[^ ]*"

有什么建议吗?

最佳答案

你可以使用

echo "$protocols" | grep -oP "$br\\s+protocols\\s*:\\s*\\[\\K[^][]*"

参见 online demo

请注意,$protocols 在双引号内(变量被引用)。

模式匹配

  • \s+ - 一个或多个空格
  • protocols - protocols
  • 这个词
  • \s*:\s* - 用零个或多个空格括起来的冒号
  • \[ - [ 字符
  • \K - 删除目前匹配的所有文本
  • [^][]* - 除了 [] 之外的零个或多个字符。

https://stackoverflow.com/questions/69048781/

相关文章:

go - 在 golang 中将 []*string 转换为 []string

swiftui - PresentationMode 触发器 "Variable X used be

ruby-on-rails - Rubocop 在 Rails 中的蓝图序列化程序自定义字段中警告

r - 如果字符串包含 x 在 R 中做 y

javascript - $(this) 在我的 jQuery 点击函数中不起作用

reactjs - 如何防止我内存的 React 组件在 React DevTools 中显示为 "

python - 您如何为加权平均平均值迭代地为数据框列赋予权重?

rust - 为什么可以在 String 上调用 Colorize trait 方法,而 Strin

python - 如何将第一列的值分成另外两列

node.js - 如何在 nodejs 中使用 getRandomValues()?