While doing day to day work we need to manipulate text file, commands outputs in many way. Our requirements continually get changed and with same we used various regex or tools to complete our task. For same way, Sometime we need to print lines between two patterns. We could do this things with both Sed and Awk.

Print Lines Between Two Patterns with Sed

Sed is really powerful tools for doing many of text manipulation work. In case we like to print lines between two pattern in sed we can use below syntax

sed -n '/<pattern1>/,/<pattern2>/p' <file-name>

commands | sed -n '/<pattern1>/,/<pattern2>/p'

We can use it in both way where we can fetch things from file or from command output to print lines between two pattern. Examples for for same are mentioned below.

root@jarvis:~# virsh net-dumpxml default|sed -n '/dhcp/,/dhcp/p'
 <dhcp>
<range start='192.168.123.2' end='192.168.123.254'/>
<host mac='52:54:00:45:ca:67' name='srv1-test' ip='192.168.123.183'/>
<host mac='52:54:00:45:ca:68' name='srv-test' ip='192.168.123.50'/>
</dhcp>

root@jarvis:~# sed -n '/root/,/sync/p'  /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync

Print Lines Between Two Patterns with Awk

We can perform same task with Awk as well which we did above with Sed command , syntax would be like below.

commands | awk '/<pattern1>/,/\/<pattern2>/'

awk '/<pattern1>/,/\/<pattern2>/' <file-name>

Because Awk is by-default nature to print things process before , so we need not to include print command in Awk syntax

Example for same are mentioned below.

root@jarvis:~# virsh net-dumpxml default|awk '/dhcp/,/\/dhcp/'
<dhcp>
<range start='192.168.123.2' end='192.168.123.254'/>
<host mac='52:54:00:45:ca:67' name='srv1-test' ip='192.168.123.183'/>
<host mac='52:54:00:45:ca:68' name='srv-test' ip='192.168.123.50'/>
</dhcp>

root@jarvis:~# awk  '/root/,/sync/'  /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync

I hope , it would help someone as it help me doing my day to day Linux commands and scripting purposes.