Replacing Lines in a Text File

From NSIS Wiki

Author: KiCHiK (talk, contrib)


Description

This script will replace every occurrence of the line "line to replace" with the line "replacement of line" in the file called "file.txt".

The script can be used to delete lines as well, by using "" as the replacement. Note however that an empty line is added to the file each time the search string is found. You can easily transform the script into one that deletes lines from a file, by not writing a line to the temp file if the search string is found in the target file (see below ["Deleting Lines from a Text File"]).

Description of variables:
$0 is a handle to the target file
$R0 is the name of a temp file
$1 is a handle to the temp file with the name $R0
$2 is the line that was read from the target file, and that is written to the temp file either changed or unchanged

The Script

ClearErrors
FileOpen $0 "file.txt" "r"                     ; open target file for reading
GetTempFileName $R0                            ; get new temp file name
FileOpen $1 $R0 "w"                            ; open temp file for writing
loop:
   FileRead $0 $2                              ; read line from target file
   IfErrors done                               ; check if end of file reached
   StrCmp $2 "line to replace$\r$\n" 0 +2      ; compare line with search string with CR/LF
      StrCpy $2 "replacement of line$\r$\n"    ; change line
   StrCmp $2 "line to replace" 0 +2            ; compare line with search string without CR/LF (at the end of the file)
      StrCpy $2 "replacement of line"          ; change line
   FileWrite $1 $2                             ; write changed or unchanged line to temp file
   Goto loop
 
done:
   FileClose $0                                ; close target file
   FileClose $1                                ; close temp file
   Delete "file.txt"                           ; delete target file
   CopyFiles /SILENT $R0 "file.txt"            ; copy temp file to target file
   Delete $R0                                  ; delete temp file

Deleting Lines from a Text File

...
   StrCmp $2 "line to remove$\r$\n" loop 0    ; if search string (with CR/LF) is found, goto loop
   StrCmp $2 "line to remove" loop 0          ; if search string is found at the end of the file, goto loop
...
Personal tools
donate
ads