首页 > 解决方案 > 下一个单词的 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,我想访问它后面的协议字符串(所以 $br br-ext 应该得到 'protocol' 而 $br-ex 应该得到 '')

我试过这个,但它似乎没有访问变量的值

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

有小费吗?

标签: regexparsingsedgrep

解决方案


您可以使用

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

查看在线演示

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

模式匹配

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

推荐阅读