3
set NLM=^


set NL=^^^%NLM%%NLM%^%NLM%%NLM%
SET memoli=%token:QMZ=%NL%%%
echo %memoli%>>%tmp%\list2.txt

I cant change the string "QMZ" with a new line. How to do that?

Rıdvan Çetin
  • 163
  • 4
  • 16
  • 2
    See this [nasty hack](http://stackoverflow.com/questions/6379619/explain-how-dos-batch-newline-variable-hack-works) - or switch to a sane language - python, ruby, powershell.. – Blorgbeard Jul 22 '14 at 02:35
  • SET memoli=%token:QMZ=%NL%%% This doesn't work. – Rıdvan Çetin Jul 22 '14 at 02:37
  • You need the entire script including blank lines. Read and understand the linked question. – Blorgbeard Jul 22 '14 at 02:39
  • @RıdvanÇetin I tried as well and nothing works. I suggest [Blorgbeard](http://stackoverflow.com/questions/24877969/replace-string-with-a-new-line-in-batch#comment38640710_24877969)'s suggestion that you switch to another language. `Ruby` and `Python` are open-source and their binaries can be easily installed. `Powershell` is also recommend over CMD scripting when in Windows. – konsolebox Jul 22 '14 at 03:14

2 Answers2

4

Very simple

setlocal EnableDelayedExpansion
set "token=HelloQMZworld"
echo !token:QMZ=^

!

It works as the batch parser parses first the multiline caret and replace it with a single linefeed.
Then in the delayed expansion phase it replaces the QMZ with a single linefeed, which is legal in that phase.

To set a new variable with the replaced string simply use

setlocal EnableDelayedExpansion
set "token=HelloQMZworld"
set newVal=!token:QMZ=^

!
echo !newVal!
jeb
  • 70,992
  • 15
  • 159
  • 202
  • Thank you for the better solution! – Rıdvan Çetin Jul 22 '14 at 13:44
  • Except that this does not actually replace the characters in the variable, it only replaces them in the printed output. – Synetech Dec 21 '15 at 05:12
  • @Synetech It works, but you didn't get a `!` into the variable by using `set "token=HelloQMZworld!"` you have to use `set "token=HelloQMZworld^!"` or set it before the delayed expansion will be enabled. I added a sample for moving the value into a variable – jeb Dec 21 '15 at 08:34
1
set LF=^


rem ** Two empty lines required
FOR /F "delims=" %%a in ("%token:QMZ=!LF!%") do (
  echo %%a>>%tmp%\list2.txt
)

I was just wandering in the codes and I just did this unconsciously. But it does the trick.

Rıdvan Çetin
  • 163
  • 4
  • 16
  • +1 It works in many cases. But it will remove or modify strings containing exclamation marks, like `myTestToken!` or `my!path!` – jeb Jul 22 '14 at 11:01
  • But you did not replace anything in the variable. What if you don’t want to print it right away? – Synetech Dec 21 '15 at 05:16
  • @jeb, yours doesn’t work with exclamation points either. `:-(` – Synetech Dec 21 '15 at 05:29