Q. I want to change the formatting of a file. I just wanted to remove all blank lines from text file. How do I achieve this task w/o spending much time?

A. Yes, you do not have to waste your time making manual changes to files. Both Linux and UNIX systems come with file manipulation tools that can be used to remove all blank lines very quickly.

Advertisement

Task: Remove blank lines using sed

Type the following command:
$ sed '/^$/d' input.txt > output.txt

Task: Remove blank lines using grep

$ grep -v '^$' input.txt > output.txt

Both grep and sed use special pattern ^$ that matchs the blank lines. Grep -v option means print all lines except blank line.

Let us say directory /home/me/data/*.txt has all text file. Use following for loop (shell script) to remove all blank lines from all files stored in /home/me/data directory:

#!/bin/sh
files="/home/me/data/*.txt"
for i in $files
do
  sed '/^$/d' $i > $i.out 
  mv  $i.out $i
done

Updated for accuracy.

🥺 Was this helpful? Please add a comment to show your appreciation or feedback.

nixCrat Tux Pixel Penguin
Hi! 🤠
I'm Vivek Gite, and I write about Linux, macOS, Unix, IT, programming, infosec, and open source. Subscribe to my RSS feed or email newsletter for updates.

31 comments… add one
  • reza Jun 14, 2013 @ 7:15

    i have a text file that in end of file have a blank line but i cant delet in by sed i have to vi it and use dd command to delet it

  • Mani Aug 27, 2015 @ 6:12

    I am using the command :-

    cat db_space.txt|sed '/-------------------- -------------------- --------------------/d'|sed '/^$/d'|sed '/^$/n'>db_space.txt

    I get the output like this,
    Database Size Used space Free space 22 GB 17 GB 5 GB in the output of text file.

    I want the output like this in the text file.

    Database Size	     Used space 	  Free space
    22 GB		     17 GB		  5 GB>

    Please let me know which command need to use?

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Your comment will appear only after approval by the site admin.