Page 1 of 1

add parentheses and batch gives error

Posted: 07 Dec 2021 00:24
by yky
I have the following batch file to extract and check the last character of strings in a file:

Code: Select all

@for /f "tokens=1 delims=;" %%A in ( C:\test.txt) do set d=%%A
@echo %d%
@echo %d:~-1%
@set c=%d:~-1%
@echo %c%
@if %c%==m @echo found it
It works as I hoped but only for the last line in the file test.txt. I'd like to have it work on every line in the file test.txt. So, I enclose commands after "do' with parentheses. Now, nothing works. I got an error message saying "@echo was unexpected at this time."

My guess is one of the variable is now empty. So, I add before the "For" command "setlocal EnableDelayedExpansion." It did not help.
I have other batch files which have several lines of commands after "do" and are enclosed with parentheses. They don't have problems. Why is this one giving the problem?

Re: add parentheses and batch gives error

Posted: 07 Dec 2021 07:58
by Squashman
You need to enable delayed expansion and use the exclamation point to reference the variable values. I have also cleaned up your code and used best practices with each command.

Code: Select all

@ECHO OFF
for /f "usebackq tokens=1 delims=;" %%A in ("C:\test.txt") do (
	set "d=%%A"
	setlocal enabledelayedexpansion
	echo !d!
	echo !d:~-1!
	set "c=!d:~-1!"
	echo !c!
	if /I "!c!"=="m" echo found it
	endlocal
)

Re: add parentheses and batch gives error

Posted: 07 Dec 2021 18:51
by yky
Thanks a lot! it works like a charm.

Anyway to mark the topic as answered? I can't find a way to do that. Also, I notice that some topics are preceded by a red file icon and there are different bell icons. Where can I find the meaning of them? Sorry for asking these basic questions. I'm quite new to this helpful forum.

Re: add parentheses and batch gives error

Posted: 08 Dec 2021 12:10
by ShadowThief
The red file means that there have been new posts since the last time you posted in the thread. The bell means that somebody quoted you.

phpBB is traditional forum software, so there aren't things like notifying people by @ShadowThief or marking topics as done; you can just leave the topic and let it sit once you're done with it.