简体   繁体   English

在批处理中用新行替换字符串

[英]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. 我不能用新行更改字符串“QMZ”。 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. 然后在延迟扩展阶段,它用单个换行替换QMZ,这在该阶段是合法的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Windows批处理文件用新字符串替换第n行或提取第n行并在变量中存储字符串 - Windows batch file to replace nth line with new string or extract nth line and store string in variable 批量查找和替换字符串添加空白行 - Batch find and replace string adds blank line 如何使用 powershell 命令用新行替换字符串? 从批处理文件中? - 双引号问题 - How can I make use a powershell command to replace a string witha new line? From within a batch file? -double quotes issue 批处理文件替换一行 - Batch file to replace a line 跳过标题行并在批处理脚本中替换文本文件中的字符串 - skip header line and replace string in text file in batch script 批处理/ Powershell为文件中的每一行替换字符串中的前2个字符 - Batch / Powershell replace first 2 characters from string for each line in file 如何使用批处理文件替换文本文件第二行中的字符串? - how to replace a string on the second line in a text file using a batch file? 使用批处理脚本查找替换变量文本的整个字符串行 - Find replace entire string line of variable text using batch script BATCH - 在文本文件中查找字符串并在该行之后添加一个新字符串 - BATCH - Find string in text file and add a new string after that line 批处理文件,用于读取文件并用新的替换字符串 - A Batch file to read a file and replace a string with a new one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM