24.07.2018 Views

Bash-Beginners-Guide

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

sandy ~><br />

As you notice, sed prints the entire file, but the lines containing the search string are printed twice. This is not<br />

what we want. In order to only print those lines matching our pattern, use the -n option:<br />

sandy ~> sed -n '/erors/p' example<br />

It is a text with erors.<br />

Lots of erors.<br />

So much erors, all these erors are making me sick.<br />

sandy ~><br />

5.2.2. Deleting lines of input containing a pattern<br />

We use the same example text file. Now we only want to see the lines not containing the search string:<br />

sandy ~> sed '/erors/d' example<br />

This is the first line of an example text.<br />

This is a line not containing any errors.<br />

This is the last line.<br />

sandy ~><br />

The d command results in excluding lines from being displayed.<br />

Matching lines starting with a given pattern and ending in a second pattern are showed like this:<br />

sandy ~> sed -n '/^This.*errors.$/p' example<br />

This is a line not containing any errors.<br />

sandy ~><br />

Note that the last dot needs to be escaped in order to actually match. In our example the expression just<br />

matches any character, including the last dot.<br />

5.2.3. Ranges of lines<br />

This time we want to take out the lines containing the errors. In the example these are lines 2 to 4. Specify this<br />

range to address, together with the d command:<br />

sandy ~> sed '2,4d' example<br />

This is the first line of an example text.<br />

This is a line not containing any errors.<br />

This is the last line.<br />

sandy ~><br />

To print the file starting from a certain line until the end of the file, use a command similar to this:<br />

sandy ~> sed '3,$d' example<br />

This is the first line of an example text.<br />

It is a text with erors.<br />

sandy ~><br />

This only prints the first two lines of the example file.<br />

The following command prints the first line containing the pattern "a text", up to and including the next line<br />

containing the pattern "a line":<br />

Chapter 5. The GNU sed stream editor 64

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!