How can I inject a newline by replacement with this script?

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 string

After:

New
String

I 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%'"
EXIT

How can I implement a newline "injection" in my script?

2

1 Answer

You can put enter image description here 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
EXIT

Note: 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.

enter image description here


Results

Before

Old string

After

New
String

Further Resources

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like