Manipulate text file by line
From NSIS Wiki
Jump to navigationJump to search
here is two function i wrote both search for whole line of text in a text file if match was found (only the first line which match) either add one line after it or replace it with another I use this to configure some .ini file
;---------------------------------------- ;cfini.nsh ; ;Functions for configurating ini files ; ; !include "cfini.nsh" ;----------------------------------------- ;----------------------------------------- ; Desc. add one line after the first instance ; of "something\r\n" is found ;----------------------------------------- ;how to use ;Push "line search" #-- line to be found ;Push "line added" #-- line to be added ;Push "C:\XXX\XXX.ini" #-- file to be searched in ; Function INIAddLine Exch $0 ;file to replace in Exch Exch $1 ;line to be added Exch Exch 2 Exch $2 ;line to be search Exch 2 Push $R0 ;save data,then use to open file Push $R1 ;save data,then use to temp file Push $R2 ;save data,then use to tmpstring ClearErrors FileOpen $R0 "$0" a FileOpen $R1 temp.ini w FileRead $R0 $R2 IfErrors +11 ;search for a string StrCmp "$2" $R2 +4 0 StrCmp "$2$\r$\n" "$R2" +6 0 ;not found yet Filewrite $R1 $R2 GOTO -5 ;add a line Filewrite $R1 $R2 Filewrite $R1 "$\r$\n$1" GOTO -8 Filewrite $R1 $R2 Filewrite $R1 "$1$\r$\n" GOTO -11 ;done FileClose $R0 FileClose $R1 ;use the temp to replace the original file Delete "$0" CopyFiles temp.ini "$0" Delete "$OUTDIR\temp.ini" POP $R2 ;restore POP $R1 ;restore POP $R0 ;restore POP $0 POP $1 POP $2 FunctionEnd
;----------------------------------------- ; Desc. replace one line after the first instance ; of "something\r\n" is found ;----------------------------------------- ;how to use ;Push "line search" #-- line to be found ;Push "line replacing" #-- line to be added ;Push "C:\XXX\XXX.ini" #-- file to be searched in ; Function INIChgLine Exch $0 ;file to replace in Exch Exch $1 ;line to be changed Exch Exch 2 Exch $2 ;line to be search Exch 2 Push $R0 ;for open file Push $R1 ;for temp file Push $R2 ClearErrors FileOpen $R0 "$0" a FileOpen $R1 temp.ini w FileRead $R0 $R2 IfErrors +9 ;search for a string StrCmp "$2" $R2 +4 0 StrCmp "$2$\r$\n" $R2 +5 0 ;not found yet Filewrite $R1 $R2 GOTO -5 ;change a line Filewrite $R1 "$1" GOTO -7 Filewrite $R1 "$1$\r$\n" GOTO -9 ;done FileClose $R0 FileClose $R1 ;use the temp to replace the original file Delete "$0" CopyFiles temp.ini "$0" Delete "$OUTDIR\temp.ini" POP $R2 POP $R1 pop $R0 POP $0 POP $1 POP $2 FunctionEnd