Showing posts with label How to remove empty lines from a file in UNIX or Linux. Show all posts
Showing posts with label How to remove empty lines from a file in UNIX or Linux. Show all posts

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$