You are not logged in.

#1 11 Aug 2014 00:42

mc510
New Member
Registered: 11 Aug 2014
Posts: 2

Trouble with variables containing ampersands!

I'm using a FOR statement to read text from a directory listing and parse it each line into three variables.  Some of the file names contain the ampersand character, and I'm having problems working with the variable in those cases. I'm trying to get this simple test case to work before moving on to some (only slightly) more complex steps:

FOR /F "tokens=1,2,3 delims=@." %%G IN (DIR /a-h-d /b /o:n) DO (SET artist=%%G & CALL :printlines)

:printlines
ECHO %artist%
GOTO :eof

When %artist% contains and ampersand, DOS tries to execute the portion after the ampersand.  If I try this...

ECHO "%artist%"

...it doesn't try to execute, but it prints unwanted quotes around my text (and also adds an extra blank on the end of the string?!?!). What's the solution here?

Needless to say, I'm pretty rookie with the stuff; thanks for pointers.

Offline

#2 11 Aug 2014 01:07

mc510
New Member
Registered: 11 Aug 2014
Posts: 2

Re: Trouble with variables containing ampersands!

Okay, I think I've got it working.

Setlocal EnableDelayedExpansion
FOR /F "tokens=1,2,3 delims=@." %%G IN (DIR /a-h-d /b /o:n) DO (SET "artist=%%G" & CALL :printlines)

:printlines
ECHO !artist!
GOTO :eof

Now I can try to make it actually do what I'm wanting. Will probably come back with another lame question!

Offline

#3 11 Aug 2014 04:02

DigitalSnow
Member
From: United States
Registered: 27 Dec 2012
Posts: 24

Re: Trouble with variables containing ampersands!

As you found, Delayed Expansion is probably the best solution for your scenario.

For a good understanding of how batch works, check out jeb's and dave's answers here:
stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts

Offline

#4 11 Aug 2014 09:48

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,129

Re: Trouble with variables containing ampersands!

I try to avoid enabling delayed expansion except in cases of necessity or expedience, as it can bring its own problems due to "!" becoming a special character.

You can also do something like this:

set /p "out=%artist%" <nul & echo:

This misuses the "set /p" command to output the text in a quoted fashion (the trailing echo is due to an often useful side effect, whereby the out put won't have a new line at the end).

Last edited by bluesxman (11 Aug 2014 09:54)


cmd | *sh | ruby | chef

Offline

Board footer

Powered by