English 中文(简体)
Sed - Pattern Range
  • 时间:2024-09-08

Stream Editor - Pattern Range


Previous Page Next Page  

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 pne and prints only those pnes that match the string Paulo.

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

[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 pnes after finding the first occurrence of the pattern. The following example finds the first occurrence of the pattern The and immediately prints the remaining pnes 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 pnes 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 pnes 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 suppped 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