Replace text in a file with the contents of other file

From NSIS Wiki

Author: Instructor (talk, contrib)


This code was superseded by TextReplace_plugin

[edit] Description

Written for Megiddo_Guest in this forum thread. Script uses headers (for NSIS 2.07 and below).

[edit] Script Code

Name "Output"
OutFile "Output.exe"
 
!include "TextFunc.nsh"
!insertmacro LineFind
 
!include "WordFunc.nsh"
!insertmacro WordFind
 
Var PMEMORY
Var SIZE
 
Section
	StrCpy $0 "C:\Input.txt"      #File to replace in
	StrCpy $1 "C:\Output.txt"     #File result
	StrCpy $R0 "ReplaceIt"        #Replace string
	StrCpy $R1 "C:\Source.txt"    #File replace with content
	StrCpy $R2 "0"                #Changes to made ("0" - replace all)
	StrCpy $R3 "0"                #[Don't change it]
 
	${LineFind} "$0" "$1" "1:-2 -1" "LineFindCallback"
 
	IfErrors 0 +2
	MessageBox MB_OK "Error"
	MessageBox MB_OK "Changes: $R3"
SectionEnd
 
Function LineFindCallback
	StrCmp $PMEMORY '0' end
 
	begin:
	${WordFind} "$R9" "$R0" "E+1{" $1
	IfErrors freemem
	FileWrite $R4 "$1"
 
	StrCmp $PMEMORY '' 0 write
	FileOpen $1 $R1 a
	FileSeek $1 0 END $SIZE
	System::Alloc $SIZE
	Pop $PMEMORY
	FileSeek $1 0 SET
	System::Call 'kernel32::ReadFile(i r1, i $PMEMORY, i $SIZE, t.,)'
	FileClose $1
 
	write:
	IntOp $R3 $R3 + 1
	System::Call 'kernel32::WriteFile(i R4, i $PMEMORY, i $SIZE, t.,)'
	${WordFind} "$R9" "$R0" "+1}" $R9
	StrCmp $R3 $R2 0 begin
 
	freemem:
	StrCmp $PMEMORY '' end
	StrCmp $R7 -1 +2
	StrCmp $R3 $R2 0 end
	System::Free $PMEMORY
	StrCpy $PMEMORY 0
 
	end:
	Push $0
FunctionEnd
donate
ads