How to Remove Blank Lines from a Text File in Batch Script
Text files gathered from logs, user inputs, or web scrapes often contain unnecessary blank lines that waste space and can confuse data-processing loops. Cleaning these files makes them more compact and ensures that your subsequent scripts do not attempt to process empty data.
In this guide, we will demonstrate how to strip all empty lines from a text file using the findstr command and a for /f loop.
Method 1: The Quick Filter (FINDSTR)
The findstr command is the standard way to search for text patterns. By using a specific regular expression, we can tell it to only output lines that contain at least one character.
Implementation Script
@echo off
setlocal
set "Source=DirtyFile.txt"
set "Dest=CleanFile.txt"
:: Verify source file exists
if not exist "%Source%" (
echo [ERROR] Source file "%Source%" not found.
pause
exit /b 1
)
echo Removing blank lines from "%Source%"...
:: /r enables regular expressions
:: /v inverts the match (exclude lines that match the pattern)
:: "^$" matches empty lines (start of line immediately followed by end of line)
findstr /v /r "^$" "%Source%" > "%Dest%"
:: findstr returns 0 if matches were output, 1 if no matches were
:: output, and 2 or higher on error. With /v, return code 1 means
:: every line was blank - a valid result with an empty output file.
if %errorlevel% gtr 1 (
echo [ERROR] Failed to process file.
pause
exit /b 1
)
echo [SUCCESS] Blank lines removed. Result saved to "%Dest%".
pause
exit /b 0
The findstr return code requires careful interpretation. With /v, a return code of 1 does not indicate an error, it means no lines survived the filter (every line in the source was blank). Only return codes of 2 or higher indicate an actual failure such as a missing file or invalid syntax.
Method 2: Removing Lines that Only Contain Spaces
The ^$ regex only catches truly empty lines. If a line contains spaces, it is technically "not empty" and will stay in the file. To remove lines that are either empty or contain only spaces, use the pattern [^ ] to filter for lines that contain at least one non-space character.
@echo off
setlocal
set "Source=DirtyFile.txt"
set "Dest=CleanFile.txt"
:: Verify source file exists
if not exist "%Source%" (
echo [ERROR] Source file "%Source%" not found.
pause
exit /b 1
)
echo [PROCESS] Removing blank and space-only lines from "%Source%"...
:: We search for any line that contains at least one character that is NOT a space.
:: This naturally excludes truly empty lines AND lines consisting only of spaces.
:: IMPORTANT: Using /c: is critical when the search pattern contains spaces.
findstr /r /c:"[^ ]" "%Source%" > "%Dest%"
:: findstr errorlevel:
:: 0 = Matches found (result saved)
:: 1 = No matches found (file is now empty)
:: >1 = Actual error (e.g., file access denied)
if %errorlevel% gtr 1 (
echo [ERROR] Failed to process file.
pause
exit /b 1
)
if %errorlevel% equ 1 (
echo [INFO] No content found. "%Dest%" is empty.
) else (
echo [SUCCESS] Content-only lines saved to "%Dest%".
)
pause
exit /b 0
The findstr command uses its own limited regex syntax. One common pitfall is that it treats spaces as "OR" separators unless you use the /c:"pattern" switch. The pattern [^ ] matches any character that is not a space; if a line contains only spaces or nothing at all, it will not match and will be stripped from the output. Note that this specific pattern does not exclude lines containing only Tabs; for full whitespace support (tabs and spaces), the PowerShell approach below is recommended.
Method 3: Using a FOR Loop (Alternative)
A for /f loop, by default, skips blank lines when it reads a file. You can take advantage of this behavior to rewrite a file without its blank lines.
@echo off
setlocal disabledelayedexpansion
set "Source=DirtyFile.txt"
set "Dest=CleanFile.txt"
:: Verify source file exists
if not exist "%Source%" (
echo [ERROR] Source file "%Source%" not found.
pause
exit /b 1
)
echo Removing blank lines from "%Source%"...
(
for /f "usebackq delims=" %%A in ("%Source%") do (
set "line=%%A"
setlocal enabledelayedexpansion
echo(!line!
endlocal
)
) > "%Dest%"
echo [SUCCESS] Blank lines removed. Result saved to "%Dest%".
pause
exit /b 0
The for /f command skips blank lines by design, which is the desired behavior here. However, it also skips lines that begin with ; (the default eol character). If your input file contains lines starting with ;, such as comments in INI files, those lines will be silently removed from the output. The findstr methods do not have this limitation.
The script uses the delayed expansion toggle pattern: variables are set with delayed expansion disabled (set "line=%%A") to preserve literal ! characters, and then read with delayed expansion enabled (echo(!line!) to safely handle &, |, >, <, and other special characters during output. The echo( syntax also prevents Batch from printing ECHO is off. when a line is empty or from displaying help text when a line contains /?.
Why Cleaning Blank Lines is Important
- Loop Reliability: If you use a
forloop to process a file line-by-line, an unexpected blank line can cause the script to set a variable to an empty value, resulting in errors in subsequent logic. - File Size: In massive logs with millions of entries, unnecessary whitespace can add megabytes of pointless bloat.
- Readability: It is much easier for a human to scan a continuous block of information than one fragmented by random spacing.
Best Practices
- Verify Source File: Always check that the input file exists before processing. The
findstrcommand may create an empty output file and return a misleading exit code when the source is missing. - Encoding:
findstrworks best on standard ANSI or UTF-8 text files. If your file is in Unicode (UTF-16),findstrmay fail to recognize line breaks correctly. Convert the file encoding first or use PowerShell for Unicode input. - Preserve Ordering: The
findstrmethod preserves the exact original order of the remaining lines, which is essential for logs and sequential data. - Audit the Results: Always check the file size of your cleaned file. If it is 0 bytes, your regex may have been too aggressive, or the source file contained only blank lines.
- Choose the Right Method: Use
findstr(Methods 1 and 2) for maximum compatibility and accurate handling of all printable characters. Use thefor /floop (Method 3) when you also need to perform per-line transformations during the cleaning pass, but be aware of the;eol limitation.
Conclusion
Stripping blank lines is a fundamental maintenance task in any data-driven workflow. By mastering the findstr command and its regular expression switches, you can ensure your text files are lean, professional, and ready for high-accuracy automated processing. This small step in script preparation prevents large-scale errors in your production pipelines.