1

I have a batch script variable like this:

Set myvar=hello\nworld

And when I echo myvar, i get the whole hello\nworld literally. How can I ask it to parse my \n and intrepret it as a new line character, so that I can echo that in two lines?

Gearbox
  • 336
  • 2
  • 15
  • 2
    you can define a newline variable `\n` and use it then with `set myvar=hello!\n!world` – jeb Aug 30 '16 at 15:17

2 Answers2

2

If your question really means "How to embed a new line character in a variable?", then this is the answer:

@echo off
setlocal EnableDelayedExpansion

set myvar=hello^

world
echo !myvar!

A caret ^ character means take the next character literally, but in this case the "next character" is just a new line, so it is taken literally in the variable and the command continue until the next end of line (as usual), so the set command ends after the world line. The embedded <NL> can only be correctly processed via delayed !expansion!.

The embedded <NL> is correctly processed in other cases; for example:

for /F %%a in ("!myvar!") do echo %%a
Aacini
  • 59,374
  • 12
  • 63
  • 94
  • 1
    `The embedded can only be correctly processed via delayed !expansion!.` and in the next line you show how to use it with FOR loop parameters :-) – jeb Aug 30 '16 at 15:12
0

Imagine, there are different programming languages and \n doesn't always mean "new line" ;).

echo hello&echo.world will do what you want if you want to have it in one line of code. Otherwise, it's

echo hello
echo.world

In batch echo. means new line or if . is followed by some text it means echo the text in a new line.

MichaelS
  • 5,569
  • 5
  • 28
  • 42
  • 1
    You should not use `echo.` to leave a blank line; use `echo/` instead. See: [this post](http://www.dostips.com/forum/viewtopic.php?t=774): _"Technically, ECHO. is a serious waste of CPU cycles. ...when the script encounters "ECHO." it will not immediately print the blank line, but will first trawl through every directory that is on the %PATH% to see if there is a file called ECHO to execute"_. – Aacini Aug 30 '16 at 14:37
  • 1
    `echo hello&echo.world` are simply two commands. I wouldn't count them as a linefeed. And you can't hold them in a variable – jeb Aug 30 '16 at 15:15