SoFunction
Updated on 2025-04-09

Some bug analysis of for command

1. About colon: When a line content starts with :, use for /f "tokens=1* delims=:" %%i in ('findstr /n .* ') do echo.%%j will :
Filter out;

2. About semicolons: findstr .* You can display the line headed by semicolons in full, but it cannot be found in the for statement. You must add parameters /n to
, it seems that the for statement will ignore the lines starting with a semicolon as comment content, as if it is not the fault of findstr; and type, more and findstr not placed in the for statement are all OK;

Solutions to solve problems 1 and 2 are:

A little more complicated:

@echo off
:: will not ignore empty lines
for /f "delims=" %%i in ('findstr /n .* ') do (
set "str=%%i"
call set "str=%%str:*:=%%"
call echo "%%str%%"
)
pause

The simplest:

@echo off
:: This code ignores empty lines
for /f "delims= eol=" %%i in () do echo %%i
pause


3. In the for extension, %%~si means that the extension path contains only short file names, but during the following tests, it was found that this was not the case:

Test environment:
--------------------------------------------------------------------------------
D:\abcdefg hijk\abcd
D:\abcdefg hijk\te

Test code:
--------------------------------------------------------------------------------
@echo off
for /f "delims=" %%i in ('dir /a /b *.txt') do echo %%~si
pause

Test results:
--------------------------------------------------------------------------------
D:\ABCDEF~1\ABCDEF~
D:\ABCDEF~1\TEST~

Have you seen the last record of the test results? It actually expanded to TEST~!

I summarized the error situation, it seems to be like this: When more than one place in the path is expanded to a short file name because the directory name exceeds 11 characters, the file name + suffix name
Extended errors occur in files with less than 11 characters and spaces.