Stream Editor - Pattern Range



In the previous chapter, we learnt how SED handles an address range. This chapter covers how SED takes care of a pattern range. A pattern range can be a simple text or a complex regular expression. Let us take an example. The following example prints all the books of the author Paulo Coelho.

[jerry]$ sed -n '/Paulo/ p' books.txt

On executing the above code, you get the following result:

3) The Alchemist, Paulo Coelho, 197 
5) The Pilgrimage, Paulo Coelho, 288

In the above example, the SED operates on each line and prints only those lines that match the string Paulo.

We can also combine a pattern range with an address range. The following example prints lines starting with the first match of Alchemist until the fifth line.

[jerry]$ sed -n '/Alchemist/, 5 p' books.txt

On executing the above code, you get the following result:

3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288

We can use the Dollar($) character to print all the lines after finding the first occurrence of the pattern. The following example finds the first occurrence of the pattern The and immediately prints the remaining lines from the file

[jerry]$ sed -n '/The/,$ p' books.txt

On executing the above code, you get the following result:

2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288 
6) A Game of Thrones, George R. R. Martin, 864 

We can also specify more than one pattern ranges using the comma(,) operator. The following example prints all the lines that exist between the patterns Two and Pilgrimage.

[jerry]$ sed -n '/Two/, /Pilgrimage/ p' books.txt 

On executing the above code, you get the following result:

2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288

Additionally, we can use the plus(+) operator within a pattern range. The following example finds the first occurrence of the pattern Two and prints the next 4 lines after that.

[jerry]$ sed -n '/Two/, +4 p' books.txt

On executing the above code, you get the following result:

2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288 
6) A Game of Thrones, George R. R. Martin, 864 

We have supplied here only a few examples to get you acquainted with SED. You can always get to know more by trying a few examples on your own.

Advertisements