jax
jax

Reputation: 38623

Replace first occurrence of text in a .bat script

I need to replace the first occurrence of <?php in a .txt file with <?php this is a test from within a .bat file.

If there are further occurrences of <?php, they should not be replaced

How can I do this.

Alternatively (although more dangerous)...I could just delete the first line of the file (assuming it will be <?php) and replace it with the above, but I don't know how to do that either in batch.

Upvotes: 0

Views: 2704

Answers (2)

jeb
jeb

Reputation: 82327

Yes, you can do this (advanced) string manipulation with something like

@echo off
set "infile=C:\temp\myFile.php"
set "outfile=C:\temp\myOut.php"
setlocal DisableDelayedExpansion
set "first=1"
(
    for /f "delims=" %%A in ('"findstr /n ^^ %infile%"') do (
        set "line=%%A"
        setlocal EnableDelayedExpansion

        set "line=!line:*:=!"
        if defined first (
            if defined line (
                set "replace=!line:<?php=<?php this is a test!"
                if !line! NEQ !replace! (
                  set "first="
                  set "line=!replace!"
                )
            )
        )
        (echo(!line!)
        if not defined first (
            endlocal
            set "first="
        ) ELSE (
            endlocal
        )
    ) 
) > %outfile%

Upvotes: 1

Haukman
Haukman

Reputation: 3776

You can't do these types of (advanced) string manipulations in batch, you need a stronger language for that, for example writing a .NET console application, or using a script language like vbscript or powershell.

Upvotes: 0

Related Questions