开发者

For loop in batch file - fails when file names are given in double quotes

I开发者_JAVA技巧've a piece of code written in batch file which looks for a predefined file in a use entered folder name. This works fine if the user doesn't enter the folder name in double quotes. But when he enters in double quotes, the for loop part in the batch file fails.

CODE:

FOR /F "usebackq delims=, skip=4" %%I IN (%A%\A.txt) DO ECHO %%I

When the value for A is given in double quotes it fails with error The system cannot find the file F:\KnoB"\A.txt


Where do you get the folder name from? If you get it from a command-line argument, then change your

set A=%1

to

set A=%~1

which removes the quotes, if present.

If you're reading from the user via set /p then use

set /P A=Folder?
for %%x in (%A%) do set A=%%~x

which does the same.

Generally, if you're getting the value from somewhere that uses only a single percent for variables (e.g. arguments or for loops), then just use the ~ in there.

You also want to surround the argument to your for loop in quotes, so that folder names with spaces don't cause unpleasant surprises:

FOR /F "usebackq delims=, skip=4" %%I IN ("%A%\A.txt") DO ECHO %%I
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜