Jump to content

ReplaceInFile()


James
 Share

Recommended Posts

Hi,

Something I whipped up for, this! Quite fast for 100 lines average is about 64 milliseconds on a 994MHz :)

Someone probably has something better and simpler but it's good to learn!

#include <File.au3>

ReplaceInFile(@ScriptDir & '\test.txt', "hi", "howdy")

Func ReplaceInFile($io_file, $io_word, $io_replacement)
    Dim $Records
    $Lines = _FileCountLines($io_File)
    If Not _FileReadToArray($io_file, $Records) Then
        ConsoleWriteError("There was an error reading > " & $io_file & @CRLF)
        Exit
    ElseIf _FileReadToArray($io_file, $Records) == "" Then
        ConsoleWriteError("File was found to be blank!" & @CRLF)
    ElseIf Not @error Then
        ConsoleWrite("> File was all good!" & @CRLF)
    EndIf
    $File = FileOpen($io_file, 2)
   ; DEBUG = ConsoleWrite("+> Found: " & $Lines & " lines!" & @CRLF)
    For $ax = 1 To $Records[0]
        ConsoleWrite("+> " & $Records[$ax] & @CRLF)
        $Replace = StringReplace($Records[$ax], $io_word, $io_replacement)
        ConsoleWrite("+> " & $Replace & @CRLF)
       ;For $ay = $Lines To UBound($Lines) - 1
       ;    FileWrite($File, $Replace)
       ;Next
        FileWrite($File, $Replace & @CRLF)
        If Not @error Then
            ConsoleWrite("> Replaced String!" & @CRLF)
        Else
            ConsoleWriteError("Error replacing text!" & @CRLF)
        EndIf
    Next
    FileClose($File)
EndFunc

In the ReplaceInFile(), replace the filename and the strings to replace.

Thanks,

James

Link to comment
Share on other sites

Yeah, I was trying to make a simpler one.

Global $File = @ScriptDir&"\Replace.txt"
Global $String = "Hello,"
Global $NewString = "Hi,"

FileWrite($File, "Hello, my name is Justin.")

_StringReplaceInFile($File, $String, $NewString)

Func _StringReplaceInFile($H_File, $S_String, $S_NewString)
    $S_ReadFile = FileRead($H_File)
    FileDelete($H_File)
    $GetEachWord = StringSplit($S_ReadFile, " ")
    For $I = 1 To $GetEachWord[0]
        If $GetEachWord[$I] = $S_String Then FileWrite($H_File, StringReplace($S_ReadFile, $S_String, $S_NewString))
    Next
EndFunc
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...