首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在斜杠之间提取文本块

在斜杠之间提取文本块
EN

Stack Overflow用户
提问于 2018-10-17 15:53:09
回答 5查看 85关注 0票数 1

我有一个包含以下内容的文件:

代码语言:javascript
复制
/interface bridge
add comment="Bridge VLAN18" fast-forward=no mtu=1500 name=\
    bridge-vlan18 protocol-mode=none
/interface ethernet
set [ find default-name=ether3 ] comment="Ether3" \
    name=cobre
set [ find default-name=ether5 ] comment="Ether5" disabled=\
    yes name=cobre2
/interface bridge port
add bridge=bridge-vlan18 interface=vlan18.bonding-ptp3
add bridge=bridge-vlan18 interface=vlan18.ether13
add bridge=bridge-vlan18 interface=vlan18.eoip-funes-vlan18
add bridge=bridge-vlan18 comment="VLAN18" \
    interface=eoip-orono-vlan18 path-cost=20
add bridge=bridge-vlan18 interface=vlan18.bonding-ptp5
/ip firewall connection tracking
    set tcp-established-timeout=10m

我需要提取从"/“到”next "/“的每一个文本块,而不需要第二个斜杠。我尝试了以下方法(提取“接口桥”块):

代码语言:javascript
复制
sed -n "/^\/interface\ bridge\s$/,/^\//p" file.txt

但我明白:

代码语言:javascript
复制
/interface bridge
add comment="Bridge VLAN18" fast-forward=no mtu=1500 name=\
    bridge-vlan18 protocol-mode=none
/interface ethernet

我要得到:

代码语言:javascript
复制
/interface bridge
add comment="Bridge VLAN18" fast-forward=no mtu=1500 name=\
    bridge-vlan18 protocol-mode=none

它需要使用本地linux工具(grep、sed、awk等)。有什么我能做的建议吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-10-17 16:07:59

另一个awk

代码语言:javascript
复制
$ awk 'f && /^\//{exit} /^\/interface bridge\r?$/{f=1} f' file

/interface bridge
add comment="Bridge VLAN18" fast-forward=no mtu=1500 name=\
    bridge-vlan18 protocol-mode=none

这应该是使用/interface bridge令牌开始打印,然后退出如果处于打印模式,然后看到下一个/

票数 1
EN

Stack Overflow用户

发布于 2018-10-17 15:54:36

这被称为记录,因此在awk中,这提供了:

代码语言:javascript
复制
awk 'BEGIN{RS="/";ORS=""}/^interface bridge/{print RS $0}' file

在这里,我们将内置变量RS定义为。RS是记录分隔符。输出记录分隔符ORS被设置为空字符串,因为每个记录已经以一个字符结束。

上面的语句是这样的:如果记录以interface bridge__开头,则使用它前面的记录分隔符RS打印记录。

但这将匹配以字符串“接口桥”开头的任何记录,因此也将匹配“接口桥端口”。更清洁一点的是:

代码语言:javascript
复制
awk 'BEGIN{RS="/";ORS=""; FS=" *\n *"}
           ($1=="interface bridge"){print RS $0}' file

在这里,我们还在字段中拆分记录,这些字段是记录中的行。上面的语句读取,如果记录的第一个字段等于interface bridge__,则使用它前面的记录分隔符RS打印记录。

票数 1
EN

Stack Overflow用户

发布于 2018-10-17 17:59:26

用剪裁:

代码语言:javascript
复制
cut -z -d '/' -f -2 file.txt
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52858963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档