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,我想访问它后面的协议字符串(所以 $br br-ext 应该得到 'protocol' 而 $br-ex 应该得到 '')
我试过这个,但它似乎没有访问变量的值
echo $protocols | grep -oP "(?<=\"$br\")[^ ]*"
有小费吗?
解决方案
您可以使用
echo "$protocols" | grep -oP "$br\\s+protocols\\s*:\\s*\\[\\K[^][]*"
查看在线演示
请注意,$protocols
在双引号内(变量被引用)。
模式匹配
\s+
- 一个或多个空格protocols
- 这个单词protocols
\s*:\s*
- 用零个或多个空格括起来的冒号\[
- 一个[
字符\K
- 删除到目前为止匹配的所有文本[^][]*
[
- 除and之外的零个或多个字符]
。
推荐阅读
- pandasql - 将 pandasql 导入为 sqldf 后,获取“模块”对象不可调用错误
- email - CassandraDB 结构的扩展问题
- visual-studio - 移动文件夹时出现不支持的挂起更改错误
- r - 将 3D 散点图转换为 3D 线性图并根据颜色进行分离
- angular - angular 6 中的 angular-maps 集成
- sql - 用 char(10)+char(13) 换行符分隔数据的子字符串出错
- html - 删除子 div 的父填充
- javascript - React Native:找不到变量:需要
- mysql - 如何关闭 mysql 服务(用于复制配置)?
- rest - 通过 REST 在 bitbucket 服务器中获取分支模型