2

I am trying to remove empty lines from a text file using a Windows Batch file.

Original file:

Test 1234
Test 12

Test 11

Test 1134

Modified file:

Test 1234
Test 12
Test 11
Test 1134

*Note that the first line in the original file was also an empty line.

I have tried this, but does not really do anything:

for /F "delims=" %a in (file.txt) do echo %a
7
  • Does (for /F "delims=" %a in (file.txt) do if {%a}=={} (echo %a)) > newfile.txt work? Commented Jul 3, 2020 at 21:03
  • 2
    DOS doesn't have for /f. Are you speaking ot the Windows Command Line (cmd) instead? (then please adapt the tags) Also within a batch file, you need %%a. %a is directly on the command line only (both DOS and cmd) Commented Jul 3, 2020 at 22:54
  • 1
    @NekoMusume: for /f already ignores empty lines, so there is no need for if Commented Jul 3, 2020 at 22:55
  • 2
    findstr /v "^$" file.txt (not in DOS though) Commented Jul 3, 2020 at 22:57
  • 2
    a safer variant (but not safe) of @Neko's, @FOR /F useback^ tokens^=*^ delims^=^ eol^= %L in ("test.txt") do @echo(%L, lines over 8191 characters will be skipped. Commented Jul 4, 2020 at 3:50

1 Answer 1

1

A simple solution is:

@echo off
if exist "file.txt" %SystemRoot%\System32\findstr.exe /R "^." "file.txt" >"file.tmp"
if exist "file.tmp" for %%I in ("file.tmp") do if %%~zI == 0 (del "file.tmp") else move /Y "file.tmp" "file.txt"

FINDSTR runs a regular expression find for lines which have at least one character at the beginning of the line and so FINDSTR outputs all lines not being empty. The output by FINDSTR is redirected into temporary file file.tmp.

The created temporary file replaces the input file on being created at all (input file exists) and is not empty which means at least one non-empty line found in input file. The temporary file is deleted on being created, but being an empty file.

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

  • del /?
  • echo /?
  • findstr /?
  • for /?
  • if /?
  • move /?

See also the Microsoft documentation about Using command redirection operators for an explanation of the redirection operator >.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.