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
 

anonymous, 17 March 2006

Or even simpler:

foreach file(*html)

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

end

blueface, 13 April 2006

That does not work.

cubby, 05 October 2006

True, it would be:

foreach file (*html)

sed -i "" '/^$/d' $file

end

But you can also use:

sed -i "" '/^$/d' *.html

RF, 27 June 2007

cat filewith.txt | sed '/^$/d' >file without.txt

RICKLE, 21 November 2007

sed '/^s*$/' < input.txt > output.txt

This removes files with just white space on a line as well.

RICKLE, 21 November 2007

There is supposed to be a backslash before the s that didn't show up...

Spawn, 10 December 2007

This is crap. Do any of you have any idea how to write code on a website.

First error right off is:

bash: syntax error near unexpected token `('

Absolute crap. Doesn't work. Considering not every system will have foreach this is awfully stupid.

Gustavo, 11 December 2007

for i in *.html;do sed '/^$/d' < $i > tt;mv tt $i;done

Ismail, 20 December 2007

Sorry guys, but you make it so complicated with the scripting!

On the command line:

sed -i "" '/^$/d' *.html

Of course, I'd recommend backing up the whole directory as the "-i" option writes to the file "inplace".

Helldev, 18 January 2008

It will work...

grep -v '^$' 1.out > 4.out

Add a comment

Name:
Email or URL: (optional)
Security code
Code shown above:
 
 
© ZoneO-soft - Contact us - Start page