Jump to content
Sign in to follow this  
MyEarth

Replace text in a file

Recommended Posts

MyEarth

Hi,

I know there are many threads on this argument, but i'm searching the fastest method to replace some text in a file:

Local $hFile = "Test.txt"

$sData = "FIRSTNAME Lastname - BAT _ TIME1" & @CRLF & _
"FIRSTNAME Lastname - BAT _ TIME2" & @CRLF & _
"FIRSTNAME Lastname - BAT _ TIME3"
FileWrite($hFile, $sData)
FileClose($hFile)

$hFileOpen = FileOpen($hFile)
$ReadData = FileRead($hFileOpen)
$sNewFile = StringRegExpReplace($ReadData, '(?i:' & "TIME" & ')', "COOL")
;~ $sNewFile = StringRegExpReplace($sData, "(-)(.*)(_)", "Another Text")
FileClose($hFile)

FileOpen($hFile, 2)
FileWrite($hFile, $sNewFile)
FileClose($hFile)

1) This is the fastest method, using StringRegExpReplace?

2) How to combine 2 or more StringRegExpReplace with different pattern ( i'm totally new to this )?

Thanks

Edited by MyEarth

Share this post


Link to post
Share on other sites
Nessie

Try this:

#include<File.au3>

$sData = "FIRSTNAME Lastname - BAT _ TIME1" & @CRLF & _
"FIRSTNAME Lastname - BAT _ TIME2" & @CRLF & _
"FIRSTNAME Lastname - BAT _ TIME3"

$FileName = "Test.txt"
$hFile = FileOpen($FileName, 1)
FileWrite($hFile, $sData)
FileClose($hFile)

$hFileOpen = FileOpen($FileName)
$ReadData = FileRead($hFileOpen)
FileClose($hFileOpen)
$sNewFile = StringRegExpReplace($ReadData, '(?i:' & "TIME" & ')', "COOL")
$sNewFile = StringRegExpReplace($sNewFile, "(-)(.*)(_)", "Another Text")

$hFileOpen = FileOpen($FileName, 2)
FileWrite($hFileOpen, $sNewFile)
FileClose($hFileOpen)

Here you can see how to combine 2 or more StringRegExpReplace with different pattern ;)

Hi!


My UDF: NetInfo UDF Play with your network, check your download/upload speed and much more! YTAPI Easy to use YouTube API, now you can easy retrive all needed info from a video. NavInfo Check if a specific browser is installed and retrive other usefull information. YWeather Easy to use Yahoo Weather API, now you can easily retrive details about the weather in a specific region. No-IP UDF Easily update your no-ip hostname(s).

My Script: Wallpaper Changer Change you wallpaper dinamically, you can also download your wallpaper from your website and share it with all!   My Snippet: _ImageSaveToBMPConvert an image to bmp format. _SciteGOTO Open a file in SciTE at specific fileline. _FileToHex Show the hex code of a specified file

Share this post


Link to post
Share on other sites
kylomas

MyEarth,

Building on Nessie's example

#include<File.au3>

$sData = "FIRSTNAME Lastname - BAT _ TIME1" & @CRLF & _
"FIRSTNAME Lastname - BAT _ TIME2" & @CRLF & _
"FIRSTNAME Lastname - BAT _ TIME3"

$FileName = "Test.txt"
$hFile = FileOpen($FileName, 2)
FileWrite($hFile, $sData)
FileClose($hFile)

$hFileOpen = FileOpen($FileName)
$ReadData = FileRead($hFileOpen)
FileClose($hFileOpen)
$sNewFile = StringRegExpReplace($ReadData, 'TIME', 'COOL')              ; <--- simplified
$sNewFile = StringRegExpReplace($sNewFile, "- \w+ _", "Another Text")   ; <--- simplified

$hFileOpen = FileOpen($FileName, 2)                                     ; <---- overwrite file
FileWrite($hFileOpen, $sNewFile)
FileClose($hFileOpen)

shellexecute('test.txt')                                                ; open file with default ".txt" program

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites
MyEarth

Thanks, you guys can confirm the use of StringRegExpReplace is the fastest method to replace text in a file?

I see other func / method like:

StringReplace

_ReplaceStringInFile ( this solution don't have any wildcards ot things like that )

But i don't know what is the best to use and the fastest on larger file, i rely on your expertise

Edited by MyEarth

Share this post


Link to post
Share on other sites
JonBMN

In my opinion and from many searches, it seems StringRegExpReplace is the fastest method available.

If my answer is wrong I'm sure someone with more knowledge will chime in.

Share this post


Link to post
Share on other sites
guinness

SRER has more flexibility, though one thing for sure is _ReplaceStringInFile is designed poorly.

An improved version I submitted to the beta...

; #FUNCTION# ====================================================================================================================
; Name ..........: _ReplaceStringInFile
; Description ...: Replaces substrings in a file.
; Syntax ........: _ReplaceStringInFile($sFilePath, $sSearchString, $sReplaceString[, $iCaseSensitive = Default[, $iOccurance = Default]])
; Parameters ....: $sFilePath           - Full path of file to replace substrings.
;                  $sSearchString       - The string to evaluate.
;                  $sReplaceString      - The replacement string.
;                  $iCaseSensitive      - [optional] Flag to indicate if the operations should be case sensitive.
;                                         $STR_NOCASESENSE (0) = not case sensitive, using the user's locale (default)
;                                         $STR_CASESENSE (1) = case sensitive
;                                         $STR_NOCASESENSEBASIC (2) = not case sensitive, using a basic/faster comparison
;                                         Constants are defined in Constants.au3
;                  $iOccurance          - [optional] 0 - Only the first occurrence is replaced or 1 - all occurrences are replaced (default)
; Return values .: Success - Returns the number of occurrences found
;                  Failure - Returns -1 and sets @error to non-zero
;                  |@error = 1 - File is read-only
;                  |@error = 2 - Unable to open the file
;                  |@error = 3 - Unable to write to the file
; Author ........: Kurt (aka /dev/null) and JdeB
; Modified ......: guinness - Re-wrote the function entirely for improvements in readability.
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _ReplaceStringInFile($sFilePath, $sSearchString, $sReplaceString, $iCaseSensitive = Default, $iOccurance = Default)
    If StringInStr(FileGetAttrib($sFilePath), "R") Then Return SetError(1, 0, -1)

    ; Open the file for reading.
    Local $hFileOpen = FileOpen($sFilePath, $FO_READ)
    If $hFileOpen = -1 Then Return SetError(2, 0, -1)

    ; Read the contents of the file and store in a variable
    Local $sFileRead = FileRead($hFileOpen)
    FileClose($hFileOpen) ; Close the open file after reading

    ; Retrieve the file encoding
    Local $iFileEncoding = FileGetEncoding($sFilePath)
    ; Open the file for writing and set the overwrite flag.
    $hFileOpen = FileOpen($sFilePath, $iFileEncoding + $FO_OVERWRITE)
    If $hFileOpen = -1 Then Return SetError(3, 0, -1)

    ; Set the default parameters
    If $iCaseSensitive = Default Then $iCaseSensitive = $STR_NOCASESENSE
    If $iOccurance = Default Then $iOccurance = 1

    ; Replace strings
    $sFileRead = StringReplace($sFileRead, $sSearchString, $sReplaceString, 1 - $iOccurance, $iCaseSensitive)
    Local $iReturn = @extended

    ; Write to the open file
    FileWrite($hFileOpen, $sFileRead)
    FileClose($hFileOpen) ; Close the open file after writing
    Return $iReturn
EndFunc   ;==>_ReplaceStringInFile

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
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
Sign in to follow this  

  • Similar Content

    • WoodGrain
      By WoodGrain
      Hi All,
      I'd like to replace 'COMMA' with ',' for example:
      $myString = "COMMA" StringRegExpReplace($myString, 'COMMA', ',') Now I've tried escaping the ',' in various ways unsuccessfully, such as:
      '[,]'
      "[,]"
      '\,'
      [,] seems to work in the pattern, I just can't figure out how to use it in the replace, and it seems everyone online is only interested in removing/replacing commas lol.
      I also tried creating and using a variable as the replacement but also didn't work:
      $myComma = "," $myString = "COMMA" StringRegExpReplace($myString, 'COMMA', $myComma) I'm sure it's super simple if someone could point me in the right direction - thanks.
    • vin1
      By vin1
      i need a script that can replace words in text with other words from a words list
      it has to have 2 edit boxes input/output and a button "run"
      from word_list.txt it choses which word to replace with. words are separated with commas for multiple choice
       

       
       

       
       
      ; AutoIt GUI Example ; Created: 17/01/2005 - CyberSlug ; Modifed: 05/12/2011 - guinness ; Modifed: 09/06/2014 - mLipok #Region INCLUDE #include <AVIConstants.au3> #include <GuiConstantsEx.au3> #include <TreeViewConstants.au3> #EndRegion INCLUDE #Region GUI GUICreate("Sample GUI", 400, 420) GUISetIcon(@SystemDir & "\mspaint.exe", 0) #EndRegion GUI #Region EDIT GUICtrlCreateEdit(@CRLF & " Sample Edit Control", 10, 10, 380, 175) GUICtrlSetTip(-1, '#Region EDIT') #EndRegion EDIT #Region EDIT2 GUICtrlCreateEdit(@CRLF & " Sample Edit Control", 10, 185, 380, 175) GUICtrlSetTip(-1, '#Region EDIT') #EndRegion EDIT2 #Region BUTTON GUICtrlCreateButton("Sample Button", 10, 360, 100, 30) GUICtrlSetTip(-1, '#Region BUTTON') #EndRegion BUTTON #Region GUI MESSAGE LOOP GUISetState(@SW_SHOW) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop EndSwitch WEnd GUIDelete() #EndRegion GUI MESSAGE LOOP  
    • way1000
      By way1000
      i'm trying to create a program that let's the user type a word in an input field (gui) and when a button is pressed the letters of the word are replaced by 1 word each from a list of words in a text file
      i created the gui for it but i need help to add some more code to make it work like intented

      each letter of a word should be replaced by a word from a text file
      the text file is a source for replacing letters is a file with 2 columns separated by tab that contains the entire alphabet (26 rows)
       
      please help if possible
       
      i posted an example gui screenshot

    • Myicq
      By Myicq
      I am currently doing a project involving keeping some parameters in an internal 2d array. I am reading part of that to and from an ini file.
      As part of the reading I need to put the variables from the ini file into the 2D array. I have found _arrayinsert(), but that creates additional lines.
      Bascially I would like something as this:
      Original array:
      [1] a1 a2 a3 a4 [2] b1 b2 b3 b4 [3] c1 c2 c3 c4 And reading setting for "2" being    d1  d2  d3  d4   I should now have
      [1] a1 a2 a3 a4 [2] d1 d2 d3 d4 [3] c1 c2 c3 c4 Is there a built-in UDF or similar to do something like that already ? Or did I missing something real obvious ?
      I have rolled my own code, which works. But of course it could be improved.
      Thanks for all comments, happy to learn from you all !
       
    • Mecano
      By Mecano
      Hallo forum members,
      I am looking for a pattern to replace user= and password= between double quotes
      user="Alfa75" becomes  user="*****"
      password="xstsgSvs" becomes  password="*****"
      In my example the opposite happens, username and password is still visable 
        StringReplace or StringRegExpReplace is not my best skill
       
      Opt("MustDeclareVars", 1) Global $Config = @ScriptDir & "\config.xml" _Config() Func _Config()     If FileExists($Config) Then         Local $file = FileOpen($Config, 0)         Local $sData = FileRead($file)         FileClose($file)         Local $rData = StringRegExpReplace($sData, "(user=Chr(34)).+?(password=Chr(34)", "\1")         ;$rData = StringReplace($rData, "user=", "*****") ; <-- desired with asterisk         ;$rData = StringReplace($rData, "password=", "*****") ; <-- desired with asterisk         $rData = StringReplace($rData, "user=", "")         $rData = StringReplace($rData, "password=", "")         MsgBox(0, "config.xml : ", $rData)         ;ClipPut($rData)     Else         MsgBox(0, "config.xml : ", "Not found")     EndIf EndFunc  config.xml
      <config> <line short="LT" city="ASD" user="Alfa75" password="xstsgSvs" code="020" registered="1" period="20" /> <line short="IC" city="RTD" user="Jonh09" password="Gdte55567" code="010" registered="1" period="25" /> <line short="IB" city="UT" user="2ronals" password="B776656" code="030" registered="0" period="15" /> <line short="IC" city="RTD" user="DEjong67" password="=0gdd++00L==" code="010" registered="1" period="25" /> <line short="ST" city="AML" user="Eddy03" password=".te555=77Ai" code="036" registered="1" period="25" /> <line short="LT" city="CAS" user="BassB" password="+gdtWU=" code="0251" registered="1" period="35" /> <line short="IC" city="DT" user="lian033" password="77t--e55+=" code="015" registered="1" period="45" /> </config> desired result
      <config> <line short="LT" city="ASD" user="*****" password="*****" code="020" registered="1" period="20" /> <line short="IC" city="RTD" user="*****" password="*****" code="010" registered="1" period="25" /> <line short="IB" city="UT" user="*****" password="*****" code="030" registered="0" period="15" /> <line short="IC" city="RTD" user="*****" password="*****" code="010" registered="1" period="25" /> <line short="ST" city="AML" user="*****" password="*****" code="036" registered="1" period="25" /> <line short="LT" city="CAS" user="*****" password="*****" code="0251" registered="1" period="35" /> <line short="IC" city="DT" user="*****" password="*****" code="015" registered="1" period="45" /> </config>
×