Quit

The quit command (q) causes sed to stop reading new input lines (and stop sending them to the output). Its syntax is:

[line-address]q

It can take only a single-line address. Once the line matching address is reached, the script will be terminated.[10] For instance, the following one-liner uses the quit command to print the first 100 lines from a file:

$ sed '100q' test
...

It prints each line until it gets to line 100 and quits. In this regard, this command functions similarly to the UNIX head command.

Another possible use of quit is to quit the script after you’ve extracted what you want from a file. For instance, in an application like getmac (presented in Chapter 4) there is some inefficiency in continuing to scan through a large file after sed has found what it is looking for.

So, for example, we could revise the sed script in the getmac shell script as follows:

sed -n "
/^\.de *$mac/,/^\.\.$/{
p
/^\.\.$/q
}" $file

The grouping of commands keeps the line:

/^\.\.$/q

from being executed until sed reaches the end of the macro we’re looking for. (This line by itself would terminate the script at the conclusion of the first macro definition.) The sed program quits on the spot, and doesn’t continue through the rest of the file looking for other possible matches.

Because the macro definition files are not that long, and the script itself not that complex, the actual time saved from this version of the script is negligible. However, with a very large file, or a complex, multiline script ...

Get sed & awk, 2nd Edition 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.