myname
myname

Reputation: 29

How can I search for a string in a txt file?

Is there some way that I can search in a example.txt file for a string example?

I tried Fileread and Fileseek but it is not working yet... later I'd like to write to the file, that's why I use FileOpen with the a append attribute:

FileOpen $4 "$SYSDIR\drivers\etc\hosts" a
FileSeek $4 0 SET
FileRead $4 $1
${If} $1 != "example"
Strcmp $1 "example" end 0

Or can I walk through the file with While? But when does the file end?

Update

!define IP_AND_DISPATCHER "30.0.0.0 dispatcher"
    FileOpen $0 "$SYSDIR\drivers\etc\hosts" a
loop:

   FileRead $0 $2
   IfErrors done
   Messagebox MB_OK "$2"
      StrCmp $2 "${IP_AND_DISPATCHER}$\r$\n" 0 loop
MessageBox MB_OK "$${IP_AND_DISPATCHER} found"
FileClose $2     ;close file
Quit

done:
    FileSeek $0 0 END
    FileWrite $0 "$\r$\n" ; new line
    FileWrite $0 "${IP_AND_DISPATCHER}" ;write ip and dispatcher
    FileWrite $0 "$\r$\n" ; extra line
 FileClose $0     ;close file

Now its working, but is there a way to not write the 30.0.0.0 dispatcher so not the entire line... just, for example, the dispatcher word?

Upvotes: 1

Views: 2790

Answers (1)

Seki
Seki

Reputation: 11465

The NSIS wiki contains several examples for text files manipulations, with

  • 2 examples for searching in a file with or without comments defining function for delegating the tedious string manipulations based on StrCmp
  • and another example for writing in a file, while there is another for replacing text

You can base your own work on these examples.

Upvotes: 3

Related Questions