Tuesday, 23 April 2013

Unix: Remove blank lines in a file without creating another/temporary file

Here is a test file :

$ cat test
hi

how

are

you
$


Now, if you want to remove all the blank lines from a file , you can do it as follows:

$ cat test | grep -v  '^$' > test1

$ mv test1 test

But , here we are creating a temporary file "test1"
Now , if you want to remove all the blank lines from a file without creating temporary file, it can be done as follows:

$ sed -i '/^$/d' test

"sed -i" overwrites the file itself
so it will remove blank lines and override the file.
Now, let's run the cat command on test 

$cat test
hi
how
are
you
 $

No comments:

Post a Comment