Linux / Unix: sed Command Print Only Matching Lines

Posted on in Categories last updated October 19, 2012

I see many examples and man pages on how to do operations like search-and-replace using sed. But, I want to match a given string or a regular pattern expression and display on the screen. How do I print lines with matching pattern using sed command only under Unix like operating systems?

Howto delete empty lines using sed command under Linux / UNIX

Posted on in Categories , , last updated December 17, 2007

Q. I need to delete all empty lines but could not figure out sed command for the same? How do I delete all empty lines with sed?

A. sed is a stream editor and perfect for these kind of work.

You need to use d command under sed which is act as the delete function.

Sed Delete Empty Line Syntax

sed ‘/^$/d’ <input-file>
echo LINE | sed ‘/^$/d’
echo $VAR | sed ‘/^$/d’

So to delete all empty lines from a file called /tmp/data.txt, enter:
$ sed '/^$/d' /tmp/data.txt
To store output to another file use redirection operator:
$ sed '/^$/d' /tmp/data.txt > /tmp/output.txt

Deleting a line that matches a pattern

You can also match a word or a pattern to delete. For example
$ cat data.txt
Output:

This is a test
Linux rulez
Windows sucks
Redhat is good server disro

To delete all lines that contain a ‘Windows’ word, enter:
$ sed '/Windows/d' /tmp/data.txt > /tmp/output.data.txt
GNU Sed support -i option to edit files in place:
$ sed -i '/Windows/d' /tmp/data.txt

See more sed examples:

=> Delete text or paragraph between two sections using sed

Updated for accuracy.