We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now


DOS script to delete empty lines inside the file

calju asked
Medium Priority
Last Modified: 2010-07-27
I want to create DOS batch file to loop through file (text files) and delete all empty lines.
Watch Question

@echo off
type nul > output.txt
for /f "delims=" %%i in (%1) do echo %%i>> output.txt

Save as your_name.bat

usage: your_name file_to_parse.txt

Outputs all non-empty lines in file_to_parse to output.txt

Note that it intentionally wipes out output.txt before writing (just remove the second line to make it always append), and it also puts an endline on the last line even if you did not have one before.  Please let me know if either of these are an issue.



But if I want to sweep same file not output to output.txt? So I can use syntax like clean.bat and filename to clean is specified inside clean.bat
@echo off
IF EXIST backup.txt goto BAILOUT
copy %1 backup.txt > nul
type nul > %1
for /f "delims=" %%i in (backup.txt) do echo %%i>> %1
del backup.txt
goto end

echo Error: backup.txt exists, unable to create working file
Okay, this one will now replace the original file with the new file lacking empty lines.  It uses a file named "backup.txt" and then deletes it when it is done.  It will check to make sure it doesn't copy over an existing "backup.txt"

You said that you wanted to specify the filename inside the file.  Right now if you saved the program as clean.bat, you could run it as:

    clean myfile.txt

and it would remove the empty lines from myfile.txt.  In windows, you can just drag the text file onto clean.bat and it will likewise strip the empty lines.  This seems more convenient to me, but if you really want to specify it inside the file, I can set that up too (though not tonight :-) ).

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.