Skip to Content
sed & awk, 2nd Edition
book

sed & awk, 2nd Edition

by Dale Dougherty, Arnold Robbins
March 1997
Intermediate to advanced
432 pages
11h 31m
English
O'Reilly Media, Inc.
Content preview from sed & awk, 2nd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The AWK Programming Language, 2nd Edition

The AWK Programming Language, 2nd Edition

Alfred V. Aho, Brian W. Kernighan, Peter J. Weinberger

Publisher Resources

ISBN: 1565922255Supplemental ContentErrata Page