ZoneO-tips for Mandriva Linux

Remove empty lines with sed

I have text files with tons of empty lines, how do I get rid of those in one second?

 
 

For html or php files that I'll post on the net, I like to get rid of empty lines. Usually, they are leftovers of search and replace and I have never been able to get any of the replace functions of the editors I use to get rid of them.

Now, sed is your friend... Written a long time ago for Unix systems, sed has been ported to a variety of operating systems, including Linux. It's is a non-interactive editor that works from a command line, with no GUI, so you do not waste time opening up windows, and clicking all over the place.

So, open up a konsole (Figure 1) and move into the directory where your file resides (cd MyDirectory). And here we go with the two lines that'll do the job

sed '/^$/d' myFile > tt
mv tt myFile
Start the Konsole
Figure 1: Start the Konsole

Here is what happens:

  • sed '/^$/d' myFile removes all empty lines from the file myFile and outputs the result in the console,
  • > tt redirects the output into a temporary file called tt,
  • mv tt myFile moves the temporary file tt to myFile.

Now, you may have 100 html files to correct at the same time. That's where foreach comes in... Let's say you want to correct all files ending with .html, here is what you should do:

  • open up a konsole (Figure 1),
  • move into the directory where your html files reside,
  • type the following commands:
    foreach file (*html)
    sed '/^$/d' $file > tt
    mv tt $file
    end
  • Finished!
12/2005
 
© ZoneO-soft - Contact us - Start page