5.12 QuitThe quit command (q ) causes sed to stop reading new input lines (and stop sending them to the output). Its syntax is:
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:
$ 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, Writing sed Scripts , 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 that needs to be applied to only a small part of the file, this version of the script could be a significant timesaver. If you compare the following two shell scripts, you should find that the first one performs better than the second. The following simple shell program prints out the top 10 lines of a file and then quits: for file do sed 10q $file done The next example also prints the first 10 lines using the print command and suppressing default output: for file do sed -n 1,10p $file done If you haven't already done so, you should practice using the commands presented in this chapter before going on to the advanced commands in the next chapter. |
|