I'm trying to do a "find and replace" into a text file from batch but only on specific lines, as such:
Before:
7,U7k956ykBJ,"GenericLine"
7,SwNZVX7SwPA2,"GenericLine"
7,783bMsWVSJZ8,"LineToReplace"
7,PiUcP84ujF5z,"GenericLine"
After:
7,U7k956ykBJ,"GenericLine"
7,SwNZVX7SwPA2,"GenericLine"
2,783bMsWVSJZ8,"LineToReplace"
7,PiUcP84ujF5z,"GenericLine"
So, to be clearer, I'd like to replace that "7," to a "2," if the line contains "LineToReplace"
CodePudding user response:
In my opinion, batch is kind of clunky to be doing this in - consider PowerShell.
But, for batch, this script:
- Enables delayed variable expansion.
- Sets DestinationFile.txt to 0 bytes.
- Loops via
FOR
through the lines of a file named SourceFile.TXT. - Places each line in variable Var.
- Replaces any double quotes in Var with two single quotes (To avoid issues with IF statement.).
- Replaces search text in Var with nothing, saving results into Alt.
- If Alt does not equal Var, then Var had the desired text, get fresh unaltered copy of the line in Var, Echo out the number 2 followed by all of Var except first char.
- Else Var did not have the desired text, so echo out the line as is and unaltered.
- Sends output to DestinationFile.txt
@ECHO OFF
SetLocal EnableExtensions EnableDelayedExpansion
NUL >DestinationFile.txt 2>NUL
FOR /F "EOL=~ TOKENS=* DELIMS=~" %%L IN (SourceFile.txt) DO (
SET Var=%%L
SET Var=!Var:"=''!
SET Alt=!Var:LineToReplace=!
IF NOT "!ALT!" == "!Var!" (
SET Var=%%L
ECHO;2!Var:~1!
) ELSE (
ECHO;%%L
)
) >>DestinationFile.txt