10.8. Quitting after a match

Occasionally you want to be able to quit sed as soon as you have matched the first occurrence of a pattern, so you can carry on with some other script processing etc. The format of the quit command is:

address q 

Here’s an example. Suppose we wish to search for the following pattern /.a.*/ which means any letter, followed by an ‘a’, followed by any letter matched zero or more times. Looking at our text file this will bring up the following word on the following lines:

Line 1. band Line 2. bad Liner3. was Line 4. was 

To be able to find the first pattern (band) then quit all we need to do is put the q at the end of the sed statement.

						$ sed '/.a.*/q' quote.txt The honeysuckle band played all night long for only $90. ...

Get Linux and Unix Shell Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.