Viktor M.
Viktor M.

Reputation: 4613

Batch file: replace string in text of a file

I need some help in replacing some text in file using bat file.

I have such a template where I need to change version:

[assembly: AssemblyVersion("5.1.1000.0")]
[assembly: AssemblyFileVersion("5.1.1000.0")]

I have written the next script but cannot understand how to change this version inside text:

REM %%f is a file where I will search a string a change it
for /f "tokens=2" %%p in ('findstr /r "[0-9]\.[0-9]\.[0-9]*\.[0-9]" %%f') do (
    echo %%p
)

Output:

AssemblyVersion("5.1.1000.0")
AssemblyFileVersion("5.1.1000.0")

How can I change 5.1.1000.0 to 7.1.1000.0,for example? That all text other text remains the same, only version will be changed.

Upvotes: 0

Views: 456

Answers (2)

foxidrive
foxidrive

Reputation: 41224

This will change any string from Version("nnnnnnnnnnn") to Version("7.1.1000.0") where nnnnn is any string of characters.

@echo off
type "file.txt" | repl "(Version\()\q.*\q(\))" "$1\q7.1.1000.0\q$2" x >"newfile.txt"

This uses a helper batch file called repl.bat (by dbenham) - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

Place repl.bat in the same folder as the batch file or in a folder that is on the path.

Upvotes: 1

Magoo
Magoo

Reputation: 79982

@ECHO OFF
SETLOCAL enabledelayedexpansion

SET "oldversion=5.1.1000.0"
SET "newversion=7.1.1000.0"

(
FOR /f "delims=" %%a IN (q24144143.txt) DO (
 SET "string=%%a"
 SET "string=!string:%oldversion%=%newversion%!"
 ECHO(!string!
)
)>newfile.txt

FC q24144143.txt newfile.txt

GOTO :EOF

I used a file named q24144143.txt containing your data for my testing. Produces newfile.txt

[Revision to extract olversion first]

@ECHO OFF
SETLOCAL enabledelayedexpansion

SET "oldversion="
SET "newversion=7.1.1000.0"

FOR /f "tokens=2delims=()" %%a IN ('findstr /r "[0-9]\.[0-9]\.[0-9]*\.[0-9]" q24144143.txt') DO (
 SET "oldversion=%%~a"
)

IF NOT DEFINED oldversion ECHO could NOT FIND old version&GOTO :EOF 
ECHO(oldversion=%oldversion%

(
FOR /f "delims=" %%a IN (q24144143.txt) DO (
 SET "string=%%a"
 SET "string=!string:%oldversion%=%newversion%!"
 ECHO(!string!
)
)>newfile.txt

FC q24144143.txt newfile.txt

GOTO :EOF

Although - since you say the file is in %%f then either assign %%f to a variable or call this routine passing "%%f" as a parameter and read file "%~1"

Upvotes: 0

Related Questions