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%
)

回答1:


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)

OR

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



回答2:


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
    echo(!Item:,-1!
    endlocal
)

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.



来源:https://stackoverflow.com/questions/41387723/batch-reading-in-a-line-from-a-file-that-has-a-colon-and-exclamation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!