start page | rating of books | rating of authors | reviews | copyrights

sed & awk

sed & awkSearch this book
Previous: 5.9 Print Line NumberChapter 5
Basic sed Commands
Next: 5.11 Reading and Writing Files
 

5.10 Next

The next command (n) outputs the contents of the pattern space and then reads the next line of input without returning to the top of the script. Its syntax is:

[address]n

The next command changes the normal flow control, which doesn't output the contents of the pattern space until the bottom of the script is reached and which always begins at the top of the script after reading in a new line. In effect, the next command causes the next line of input to replace the current line in the pattern space. Subsequent commands in the script are applied to the replacement line, not the current line. If the default output has not been suppressed, the current line is printed before the replacement takes place.

Let's look at an example of the next command in which we delete a blank line only when it follows a pattern matched on the previous line. In this case, a writer has inserted a blank line after a section heading macro (.H1). We want to remove that blank line without removing all blank lines in the file. Here's the sample file:

.H1 "On Egypt"

Napoleon, pointing to the Pyramids, said to his troops: 
"Soldiers, forty centuries have their eyes upon you."

The following script removes that blank line:

/^\.H1/{
n
/^$/d
}

You can read this script as follows: "Match any line beginning with the string `.H1', then print that line and read in the next line. If that line is blank, delete it." The braces are used to apply multiple commands at the same address.

In a longer script, you must remember that commands occurring before the next command will not be applied to the new input line, nor will commands occuring after it be applied to the old input line.

You'll see additional examples of the n command in Chapter 6, along with a multiline version of this command.


Previous: 5.9 Print Line Numbersed & awkNext: 5.11 Reading and Writing Files
5.9 Print Line NumberBook Index5.11 Reading and Writing Files

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System