Getting CR into a variable

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Getting CR into a variable

#1 Post by foxidrive » 24 Feb 2014 19:36

Does this get a CR into a variable?

The question was asked elsewhere and I had never examined the technique - I can't seem to echo a CR into a file.

Code: Select all

::Define CR variable containing a carriage return (0x0D)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"

echo "%cr%">a.txt

echo a"%cr%b%cr%c%cr%d%cr%e%cr%f%cr%g%cr%"

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

Re: Getting CR into a variable

#2 Post by Squashman » 24 Feb 2014 19:45

you need to use delayed expansion.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Getting CR into a variable

#3 Post by foxidrive » 24 Feb 2014 20:34

Thanks Squashman, that's the tip!

Code: Select all

@echo off
setlocal enabledelayedexpansion
::Define CR variable containing a carriage return (0x0D)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"

echo "!cr!">a.txt

echo a"!cr!b!cr!c!cr!d!cr!e!cr!f!cr!g!cr!"

pause

jeb
Expert
Posts: 1063
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: Getting CR into a variable

#4 Post by jeb » 25 Feb 2014 17:31

Additional the cause why %CR% doesn't work.

It's the parser phase just after the percent expansion of variables, it removes all CR's.

jeb

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Getting CR into a variable

#5 Post by foxidrive » 25 Feb 2014 18:14

Thanks jeb.

Post Reply