add parentheses and batch gives error

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
yky
Posts: 5
Joined: 08 Sep 2014 17:54

add parentheses and batch gives error

#1 Post by yky » 07 Dec 2021 00:24

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?

Squashman
Expert
Posts: 4386
Joined: 23 Dec 2011 13:59

Re: add parentheses and batch gives error

#2 Post by Squashman » 07 Dec 2021 07:58

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
)

yky
Posts: 5
Joined: 08 Sep 2014 17:54

Re: add parentheses and batch gives error

#3 Post by yky » 07 Dec 2021 18:51

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.

ShadowThief
Expert
Posts: 1065
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: add parentheses and batch gives error

#4 Post by ShadowThief » 08 Dec 2021 12:10

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.

Post Reply