Batch: Reading in a line from a file that has a colon and exclamation

廉价感情. 提交于 2019-12-25 08:17:10


I'm trying to read in a line from a file that contains a colon and exclamation point. When I echo that line, it only shows everything AFTER the colon. I need to keep the enabledelayedexpansion for more advanced code I will be doing in the do loop. But right now I just want to echo properly. Any help would be appreciated!

File would say something like:

! 12345 APX: 6.32

Code I tried was:

setlocal EnableDelayedExpansion
cd C:\Users\jwagh\Desktop\
for /f "usebackq delims=" %%a in (test.txt) DO (
setlocal DisableDelayedExpansion
 echo %%a
 set line=%%a
 set example=%line:~0,-1%
 echo %example%


Probably disabling delayedexpansion is the only practicable solution, but depending on your data, setting delims to ! would set %%a to the entire line, minus the initial ! (assuming obviously only one !-sequence of known length and it always leads the line)


for /f "usebackq delims=!" %%a in (%FamilyFile%) DO echo ^^!%%a


The only bullet-proof solution is to disable delayed expansion during expansion of %%a, and to enable it only when it is actually needed. For example, something like this:

setlocal DisableDelayedExpansion
for /F "usebackq delims=" %%a in (%File%) do (
    set "Item=%%a"
    setlocal EnableDelayedExpansion

Since localised environments created by setlocal/endlocal blocks are limited in terms of nesting, you need to put also endlocal within a loop. Regard that after endlocal, all environment changes since the latest setlocal get lost.

But now for something completely different (related to revision 3 of the question):
I assume %File% holds a quoted file path/name, because of the usebackq option.
Let me recommend not to include the quotes in the variable value, using the following syntax:

set "File=D:\Data\file.ext"  & rem // (particularly note the position of the opening quote)

Reference this post to learn why this is better.