Replace all text before a string on a line

From NSIS Wiki

Author: Afrow UK (talk, contrib)


Description

This function was written for vbgunz. It searches a text file for a specified string, and once found replaces everything before it on that same line with another specified string.

Note: It will only find one occurrence of the string per line starting from the end of the line. It will also search the whole text file (not just once and stop) for occurrences of the specified string and do all replacements.

Usage

${ReplaceBefore} "Before" "With" "$INSTDIR\in.txt"

Example

$INSTDIR\Afrow.txt file content:

Hello my name is Afrow UK, or rather, Stuart.
Afrow UK is the dude!

Function Call

${ReplaceBefore} "Afrow UK" "Big " "$INSTDIR\Afrow.txt"

$INSTDIR\Afrow.txt new file content:

Big Afrow UK, or rather, Stuart.
Big Afrow UK is the dude!

The Function

!macro ReplaceBefore Before With In
Push "${Before}"
Push "${With}"
Push "${In}"
 Call ReplaceBefore
!macroend
!define ReplaceBefore "!insertmacro ReplaceBefore"
 
Function ReplaceBefore
 Exch $R0 ; file
 Exch
 Exch $R1 ; replace string
 Exch 2
 Exch $R2 ; find string
 Exch 2
 Push $R3 ; tmp file
 Push $R4 ; file handle
 Push $R5 ; tmp file handle
 Push $R6 ; line read
 Push $R7 ; loop char count
 Push $R8 ; input string len
 Push $R9 ; misc
 
 GetTempFileName $R3
 FileOpen $R4 $R0 r
 FileOpen $R5 $R3 w
 
  StrLen $R8 $R2
 
 Read:
  ClearErrors
  FileRead $R4 $R6
  IfErrors Done
 
  StrCpy $R7 0
 
 LineScan:
  IntOp $R7 $R7 - 1
  StrCpy $R9 $R6 $R8 $R7
  StrCmp $R9 "" Write
  StrCmp $R9 $R2 0 LineScan
 
   StrCpy $R6 $R6 "" $R7
   StrCpy $R6 $R1$R6
 
 Write:
  FileWrite $R5 $R6
  Goto Read
 
 Done:
 
 FileClose $R4
 FileClose $R5
 
 SetDetailsPrint none
 Delete $R0
 Rename $R3 $R0
 SetDetailsPrint both
 
 Pop $R9
 Pop $R8
 Pop $R7
 Pop $R6
 Pop $R5
 Pop $R4
 Pop $R3
 Pop $R2
 Pop $R1
 Pop $R0
FunctionEnd

-Stu

Personal tools
donate