-2

I want to print section (paragraph) of text between lines contains regexp, please help, how it could be done by grep, not awk or sed, or find regexp by grep and print with awk|sed. I use it in script, and regexp - is variable. param - is a pattern of extended regular expression (ERE)

awk  -v RS="<section>" "/$param/" "$FILE"   <!--it's now, but I need to find param by grep-->

example of the file:

<section>
 interface gigabitEthernet 7 // 192.168.248.200
  switchport access vlan 1
  switchport mode access
  port shutdown
<section>
 interface gigabitEthernet 8 // 
  switchport access vlan 2
  switchport mode trunk
<section>

1 Answers1

1

As it has been pointed out, grep is not the ideal tool for this task. However it may work if you use two of them ;-)

grep -Pzo "(?s)^$|<section>([^<]*${param}[^<]*)" "$FILE" | grep -v '<section>'

-Pzo activates perl regular expressions, multi-line matching and limits output to the matched part, see this related question.

Note that the output differs from your awk statement's output in whitespace and not all grep implementations support -P.

Community
  • 1
  • 1
Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
  • Thanks a lot, but can it be done with grep -E to find paragraph, or can I done it something else? pattern for param is extended regular expression (ERE) – Сергей Смирнов Apr 17 '15 at 06:26
  • @Сергей Смирнов: I don't think it can be done with `-E`. After all, `grep` is still a line-based tool. But you may find that your ERE snippet works with the PCRE engine as well. ERE is not strictly a subset of PCRE, but most ERE expressions should work (source: this [answer](http://stackoverflow.com/a/1428905/4024473) on a related topic) – Michael Jaros Apr 17 '15 at 14:52