Saturday, April 2, 2011

How to remove empty lines from a file in UNIX or Linx

volcano@volcano-laptop:~/shellscript/empty$ cat testempty
hi first line

above line is empty
hi dude

above line is empty
volcano@volcano-laptop:~/shellscript/empty$ sed '/^$/d' testempty > testwithoutempty
volcano@volcano-laptop:~/shellscript/empty$ cat testwithoutempty
hi first line
above line is empty
hi dude
above line is empty
volcano@volcano-laptop:~/shellscript/empty$

volcano@volcano-laptop:~/shellscript/empty$ grep -v '^$' testempty > without
volcano@volcano-laptop:~/shellscript/empty$ cat without
hi first line
above line is empty
hi dude
above line is empty

One exception case is available for empty line removal. That is line will be empty but it will have space or tab characters. To handle that, we can use the below command format.


grep -v '^[]*]$'  oldfile > newfile

volcano@volcano-laptop:~/shellscript/empty$ cat test
hi first line

above line is empty
hi dude

above line is empty
   
volcano@volcano-laptop:~/shellscript/empty$ grep -v '^[         ]*$' test > newtest
volcano@volcano-laptop:~/shellscript/empty$ cat newtest
hi first line
above line is empty
hi dude
above line is empty
volcano@volcano-laptop:~/shellscript/empty$

volcano@volcano-laptop:~/shellscript/empty$ sed '/^$/d' test
hi first line
above line is empty
hi dude
above line is empty
   
volcano@volcano-laptop:~/shellscript/empty$ sed '/^[    ]*$/d' test
hi first line
above line is empty
hi dude
above line is empty
volcano@volcano-laptop:~/shellscript/empty$

5 comments:

lee woo said...

The purpose of education is to replace an empty mind with an open one. See the link below for more info.

#empty
www.mocsbar.com

Cindy Dy said...


You have a wonderful blog. This is really worth to read and it helps a lot of people to learn new information about this deceased. Please keep on posting. Thank you.

Sorn
www.gofastek.com

lee woo said...

Love it! Very interesting topics, I hope the incoming comments and suggestion are equally positive. Thank you for sharing this information that is actually helpful.


ufgop.org
ufgop.org

sarah lee said...

I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.


edupdf.org

oracle R12 said...

I learnt very good information from this article , This is really worth to read and it helps a lot of people to learn new information about this deceased.Is this above commands used for all unix flavours?
Thank you.
oracle R12 training