提取斜线之间的文本块

时间:2018-10-17 15:53:09

标签: linux bash sed

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

/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

我需要将每个文本块从“ /”提取到下一个“ /”,而没有第二个斜杠。我尝试了以下操作(提取“接口桥”块):

sed -n "/^\/interface\ bridge\s$/,/^\//p" file.txt

但是我得到了

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

我需要获得:

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

需要使用本地linux工具(grep,sed,awk等)。任何建议我该怎么做?

5 个答案:

答案 0 :(得分:1)

这称为记录,因此在中给出:

awk 'BEGIN{RS="/";ORS=""}/^interface bridge/{print RS $0}' file

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

上面的语句显示为,如果记录以interface bridge开头,则在记录前用记录分隔符RS打印记录。

但这将匹配任何以字符串“ interface bridge”开头的记录,也将匹配“ interface bridge port”。会更干净一点:

awk 'BEGIN{RS="/";ORS=""; FS=" *\n *"}
           ($1=="interface bridge"){print RS $0}' file

在这里,我们还将记录拆分为字段,即记录中的行。上面的语句显示为:如果记录的第一个字段等于interface bridge,则在记录前用记录分隔符RS打印记录。

答案 1 :(得分:1)

另一个<xsl:value-of select="substring-before(dc:subject, '&#xD;')"/>

awk

这应显示为使用$ 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

答案 2 :(得分:1)

切好:

cut -z -d '/' -f -2 file.txt

答案 3 :(得分:0)

您可以在x中使用sed选项。

  

x:交换保留和模式空间的内容。

$ sed -n -e '/\/interface bridge$/,/^\//{x;p}' inputFile

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

请注意,它将在开头添加一个额外的空行。

或者这个

$ sed -n -e '/\/interface bridge$/,/^\//{/\/interface ethernet$/d;p}' inputFile
/interface bridge
add comment="Bridge VLAN18" fast-forward=no mtu=1500 name=\
    bridge-vlan18 protocol-mode=none

答案 4 :(得分:0)

这可能对您有用(GNU sed):

sed '/^\/interface bridge\s*$/{:a;n;/^\//!ba};d' file

如果一行以/开头,请打印并将其替换为下一行。如果该行不是以/开头,则将其打印并重复直到行确实以/开头,然后将其删除。其他所有行均被删除。