Ranges and Occurrences


The range of lines to be processed by sed can be restricted using ranges. A line range can consist of a single-line definition or a range of lines. For example (using the substitute command for illustration):

 5s/this/that/ 

replaces occurrences of this with that on line 5. We could specify that only the first five lines are operated upon, such as:

 1,5s/this/that/ 

where 1,5 represents the range of lines one through five. If instead we wanted the range of line five to the end of the file, this could be provided using the end of file symbol $:

 5,$s/this/that/ 

When we provide no range, it applies to all lines. One final useful modifier is the ! command. This tells sed not to apply to the given line range. Using this with our prior example:

 5,$!s/this/that/ 

This tells sed to apply the substitution to all lines, excluding line five through the end of the file.

Rather than specify line ranges, we can also define ranges based upon patterns. Consider the following example:

 '/^The/s/this/that/' 

This substitutes that for this for any line that begins with The . We can also perform substitution between pattern ranges, as:

 '/start/,/end/s/index/idx/g' 

This replaces index with idx after a line containing start is found and ends the replacement after a line containing end is found.




GNU/Linux Application Programming
GNU/Linux Application Programming (Programming Series)
ISBN: 1584505680
EAN: 2147483647
Year: 2006
Pages: 203
Authors: M. Tim Jones

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net