Tuesday, August 21, 2007

remove blank lines using grep or sed

Here's a quick rundown on how to remove blank lines between contents from text files using linux command sed and grep.

Suppose we have a text file named testfile.txt . With the below content samples.

# cat testfile.txt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1
2
3



5
6
7
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As you can see from above content, there are multiple blank lines. Our objective here is to eliminate those blank lines lines, thus suppressing the text file.

This entry covers how to remove blank lines of text files using sed and grep. As follow

# grep -v '^$' testfile.txt

# sed -e '/^$/d' testfile.txt


You can redirect the output from your screen into a file using linux redirection approach. As follows:

# grep -v '^$' testfile.txt > testfile1.txt

# sed -e '/^$/d' testfile.txt > testfile2.txt


Verify that we have achieved our objective of removing blank lines from a file.

# cat testfile.txt
~~~~~~~~~~~~~~~~~~~~
1
2
3
5
6
7
~~~~~~~~~~~~~~~~~~~~

Done!

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy