Jump to content

[Help] How to replace a string in a line from a text file?


Recommended Posts

@jackylee0908

You could use:

  • FileOpen() with $FO_OVERWRITE to open the file, overwriting the previous content of the file when modifying it;
  • FileRead() to read the content of the file in a variable;
  • StringReplace or SRER() to replace the characters you want to replace;
  • FileWrite() to write the content of the file with replaced chracters;
  • FileClose() to close the handle of the file previousely opened.

Then, put all these functions in a loop (list of file get through _FileListToArray() or FileFind* functions) :)

Click here to see my signature:

Spoiler

ALWAYS GOOD TO READ:

 

Link to comment
Share on other sites

@jackylee0908

A few days ago, i wrote a small example script for multiple search&replace (nothing spectacular ;)  )

The search&replace values are stored in ReplaceArr01-EN.txt for later use in an array.

The original file will not be changed but saved under *_new* .

File : SearchReplaceV4-EN.au3

; @Musashi : 2019-09-11 / 10:50

#include <File.au3>
#include <Array.au3>
#include <StringConstants.au3>
#include <Date.au3>

Global $sReplaceFile, $sFileRead, $sReplaceFileName, $sReplaceFileExt, $sReplaceFileNew
Global $aReplaceArr, $sFilePathReplaceArr
Global $iError, $iReplacements, $iFileEncoding, $bValueChanged = False

; [optional] : Globals are for time measurement only :
Global $hTimer, $fTimerDiff, $iTimerHours = 0, $iTimerMins = 0, $iTimerSecs = 0, $iTimerMilliSecs = 0

$sReplaceFileName = "Testtext01-EN"
$sReplaceFileExt  = ".txt"
$sReplaceFile     = @ScriptDir & "\" & $sReplaceFileName & $sReplaceFileExt
$sReplaceFileNew  = @ScriptDir & "\" & $sReplaceFileName & "_New" & $sReplaceFileExt

If Not FileExists($sReplaceFile) Then
    ConsoleWrite('! ---> File : ' & $sReplaceFile & ' not found -> EXIT' & @CRLF)
    Exit
EndIf

; Array with ' Search & Replace' values :
;    Delimiter = #|#
;    Row 0 = search value
;    Row 1 = replace value
;    Row 2 = if semicolon (;) -> do not replace element (= commented out)
$sFilePathReplaceArr = @ScriptDir & "\ReplaceArr01-EN.txt"
_FileReadToArray($sFilePathReplaceArr, $aReplaceArr, BitOR($FRTA_COUNT, $FRTA_ENTIRESPLIT) , "#|#")
_ArrayDisplay($aReplaceArr, "Replace Array") ; *** for display only

; [optional] : start timer
$hTimer = TimerInit()

$sFileRead = FileRead($sReplaceFile)
If @error Then
    ConsoleWrite('! ---> File : ' & $sReplaceFile & ' not open -> EXIT' & @CRLF)
    Exit
EndIf

For $i = 1 To $aReplaceArr[0][0]
    ; If a semicolon occurs in column 2 ==> do not modify
    If Not StringInStr($aReplaceArr[$i][2], ';') Then
        ConsoleWrite('+ ===> Row <' & $i & '> : Replace <' & $aReplaceArr[$i][0] & '> with <' & $aReplaceArr[$i][1] & '>' & @CRLF)

        $sFileRead     = StringRegExpReplace($sFileRead, '(?i)' & $aReplaceArr[$i][0], $aReplaceArr[$i][1])
        $iError        = @error
        $iReplacements = @extended
        If Not $iError Then
            $bValueChanged = True
            ConsoleWrite('< -----> <' & $aReplaceArr[$i][0] & '> ' & $iReplacements & ' times replaced with <' & $aReplaceArr[$i][1] & '>' & @CRLF)
        EndIf
    Else
        ConsoleWrite('> ===> Row <' & $i & '> commented out !' & @CRLF)
    EndIf
Next

If $bValueChanged Then
    Local $iFileEncoding = FileGetEncoding($sReplaceFile)
    Local $hFileOpen = FileOpen($sReplaceFileNew, BitOR($iFileEncoding, $FO_OVERWRITE))
    FileWrite($hFileOpen, $sFileRead)
    FileClose($hFileOpen)
EndIf

; [optional] : end timer
$fTimerDiff = TimerDiff($hTimer)
$iTimerMilliSecs = Int(Mod($fTimerDiff, 1000))
_TicksToTime(Int($fTimerDiff), $iTimerHours, $iTimerMins, $iTimerSecs)
$sString = StringFormat("%02d:%02d:%02d.%03d (Std:Min:Sek.Millisek)", $iTimerHours, $iTimerMins, $iTimerSecs, $iTimerMilliSecs)
ConsoleWrite("Duration = " & $sString & @CRLF)

Maybe it helps.

SearchReplaceV4-EN.au3 Testtext01-EN.txt ReplaceArr01-EN.txt

Edited by Musashi

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Link to comment
Share on other sites

@jackylee0908

An alternative way to replace a substring is https://www.autoitscript.com/autoit3/docs/libfunctions/_ReplaceStringInFile.htm
My example above is more designed to replace multiple strings via array (but it also works with only one string, of course ;) )

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

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...