简体   繁体   中英

Replace string with a new line in Batch

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?

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!
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.

Perhaps following batch code works for what you want to do:

@echo off
rem Define environment variable "token" with an example string.
set token=Line1QMZLine2QMZLine3
setlocal EnableDelayedExpansion
:NextLine
for /F "delims=QMZ tokens=1,*" %%I in ("!token!") do (
   echo %%I>>"%tmp%\list2.txt"
   set "token=%%J"
   if not "!token!"=="" goto NextLine
)
endlocal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM