Home > Mobile >  Batch find and replace only on lines that contain a specific text
Batch find and replace only on lines that contain a specific text

Time:05-20

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:

  1. Enables delayed variable expansion.
  2. Sets DestinationFile.txt to 0 bytes.
  3. Loops via FOR through the lines of a file named SourceFile.TXT.
  4. Places each line in variable Var.
  5. Replaces any double quotes in Var with two single quotes (To avoid issues with IF statement.).
  6. Replaces search text in Var with nothing, saving results into Alt.
  7. 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.
  8. Else Var did not have the desired text, so echo out the line as is and unaltered.
  9. 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

  • Related