I have a batch script that can replace text, and I want it to replace strings that are followed by a newline of text below the original. An example would be as follows:
Before:
Old stringAfter:
New
StringI have tried a number of newline commands used in batch (some of which are found on Stack Exchange sites) and none of them work. I believe it is because of the syntax of the script. Here is the script I am working with:
@echo off
setlocal enableextensions disabledelayedexpansion
set search=Old string
set replace=New string
set textFile=Test.txt
:PowerShell
SET PSScript=%temp%\~tmpStrRplc.ps1
ECHO (Get-Content "%~dp0%textFile%").replace("%search%", "%replace%") ^| Set-Content "%~dp0%textFile%">"%PSScript%"
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%PSScript%'"
EXITHow can I implement a newline "injection" in my script?
21 Answer
You can put in place of the space between the replacement string where you want the newline (
CRLF) to be placed to get the expected result—backtick "r" backtick "n" (see below).
This only requires that one small change to the existing script and it'll work as expected per your description and example output results.
Script
@echo off
setlocal enableextensions disabledelayedexpansion
set search=Old string
set replace=New`r`nstring
set textFile=Test.txt
:PowerShell
SET PSScript=%temp%\~tmpStrRplc.ps1
ECHO (Get-Content "%~dp0%textFile%").replace("%search%", "%replace%") ^| Set-Content "%~dp0%textFile%">"%PSScript%"
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%PSScript%'"
PAUSE
EXITNote: Be sure to not put any spaces between the two strings in the replace= variable to ensure there is no trailing or leading spaces in the new string with the newline as you need.
Results
Before
Old stringAfter
New
StringFurther Resources
Escape characters, Delimiters and Quotes
Special characters Special characters are used to format/position string output. `r`n Carriage return + New lineBacktick Key