Jump to content
Sign in to follow this  

ReplaceStringInFile Suggestion

Recommended Posts


Func __ReplaceStringInFile($szFileName, $szSearchString, $szReplaceString, $fCaseness = 0, $fOccurance = 1)
    Local $iRetVal = 0
    Local $nCount, $sEndsWith
    ; Check if file is readonly ..
    If StringInStr(FileGetAttrib($szFileName), "R") Then Return SetError(6, 0, -1)
    ;== Read the file into an array
    Local $hFile = FileOpen($szFileName, $FO_READ)
    If $hFile = -1 Then Return SetError(1, 0, -1)
    Local $s_TotFile = FileRead($hFile, FileGetSize($szFileName))
    If StringRight($s_TotFile, 2) = @CRLF Then
        $sEndsWith = @CRLF
    ElseIf StringRight($s_TotFile, 1) = @CR Then
        $sEndsWith = @CR
    ElseIf StringRight($s_TotFile, 1) = @LF Then
        $sEndsWith = @LF
        $sEndsWith = ""
    Local $aFileLines = StringSplit(StringStripCR($s_TotFile), @LF)
    ;== Open the output file in write mode
    Local $iEncoding = FileGetEncoding($szFileName)
    Local $hWriteHandle = FileOpen($szFileName, $iEncoding + $FO_OVERWRITE)
    If $hWriteHandle = -1 Then Return SetError(2, 0, -1)
    ;== Loop through the array and search for $szSearchString
    For $nCount = 1 To $aFileLines[0]
        If StringInStr($aFileLines[$nCount], $szSearchString, $fCaseness) Then
            $iRetVal = $iRetVal + 1
            If $fOccurance = $iRetVal Then
                $aFileLines[$nCount] = StringReplace($aFileLines[$nCount], $szSearchString, $szReplaceString, 1 - $fOccurance, $fCaseness)
    ;== Write the lines back to original file.
    Local $Tempfile = _TempFile()
    FileWrite($Tempfile, _ArrayToString($aFileLines, @LF, 1))
    FileMove($Tempfile, $szFileName, 1)
    Return $iRetVal
EndFunc   ;==>__ReplaceStringInFile

Yes, I know guinness improved the ReplaceStringInFile function in terms of speed and  efficiency but hear me out. I made some changes to the original myself that increased the speed of the writing and more importantly for me change the occurrence option so the function would only replace that specific occurrence of string.

I not saying use my code. What I am suggesting is to add extra functionally to the ReplaceStringInFile so there is a option to replace a specific occurrence.

I could not think of a way to do this with the new one guinness made so above is just an example of how I did it with the old one.

I have also attached the file.au3 file.


No problem can withstand the assault of sustained thinking.Voltaire


Share this post

Link to post
Share on other sites

Looking at the the code you assume every line ends with the same EOL character and then when you come to write the data to the file you just use a linefeed character. As for adding your suggestion, I don't feel it appeals to the wider audience. Thanks.

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

    • XinYoung
      By XinYoung
      Hello all! I hope everyone is enjoying their holiday festivities. 
      I'm working on a script that involves copying a string of text from an Excel workbook and searching for it in a particular website's search tool. If a result is found, it will do something. If not, it will do something else.
      So far, it can successfully execute the search -- and then it shows me the results in an array.
      Screenshot of the successful search:

      The search results in an array:

      Here's the code (sorry for all my comments):
      ;~ All the functions this app performs require the external files listed here. So, theyre "included". #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <WinAPIFiles.au3> #include <Array.au3> #include <File.au3> #include <Excel.au3> #include <DateTimeConstants.au3> #include <MsgBoxConstants.au3> #include <WinAPIShellEx.au3> #include <Date.au3> #include <ComboConstants.au3> #include <Misc.au3> #include <WinAPIProc.au3> #include <WinAPISys.au3> #include <WinAPIConstants.au3> #include <Crypt.au3> #include <ColorConstants.au3> #include <guimenu.au3> #include <IE.au3> ;~ Kill all functions and close the app at anytime by pressing F4. HotKeySet("{F4}", "_Exit") ;~ Keep track whether or not a file is selected. When the program first opens, a file is currently not selected. Global $FileChosen = 0 ;~ The app must remember certain strings of text: ;~ 1. Login page Global $urlBBLogin = "website.com" ;~ 2. Credentials Global $bbUsername = "USER" Global $bbPassword = "PW" ;~ 3. Search page Global $urlBBCourseSearch = "website.com/search" ;~ When you launch the app, the UI gets built and is displayed to the user in the center of the screen. the "Function" buttons are disabled until a file is chosen. $MasterUI = GUICreate("Master Re-Creator", 469, 145, -1, -1) $Label1 = GUICtrlCreateLabel("Choose the Excel file", 8, 8, 103, 17) $Select = GUICtrlCreateButton("Select File", 16, 32, 75, 25) $FileName = GUICtrlCreateLabel("[No File Selected]", 104, 40, 88, 17) $Group1 = GUICtrlCreateGroup("Functions", 8, 72, 449, 65) $CheckCourse = GUICtrlCreateButton("Check Courses Exist", 24, 96, 123, 25) GUICtrlSetState(-1, $GUI_DISABLE) $DeleteCourse = GUICtrlCreateButton("Delete Courses", 168, 96, 123, 25) GUICtrlSetState(-1, $GUI_DISABLE) $CopyCourse = GUICtrlCreateButton("Copy Courses", 312, 96, 123, 25) GUICtrlSetState(-1, $GUI_DISABLE) GUICtrlCreateGroup("", -99, -99, 1, 1) GUISetState(@SW_SHOW) ;~ While the UI is open, it listens for triggers (in this case, button presses). While 1 $UI = GUIGetMsg() Select ;~ If the app is closed, the _Exit() function is performed (same function the F4 hotkey calls). Case $UI = $GUI_EVENT_CLOSE _Exit() ;~ The user has clicked the "Select File" button, the _LocateGetFileName() function is performed. Go there. Case $UI = $Select _LocateGetFileName() ;~ The user has clicked the "Check Courses Exist" button. Case $UI = $CheckCourse _CheckCourses() ;~ Other buttons are not ready EndSelect WEnd ;~ The user clicked the "Select File" button. This function will execute now. Func _LocateGetFileName() ;~ Prepare the app to take note of the details of a file. Local $sDrive = "", $sDir = "", $sFileName = "", $sExtension = "" ;~ Open a File Explorer to allow the user to select a file. Only Excel files are allowed to be chosen. Global $ChosenFileName = FileOpenDialog("Locate File", @DesktopDir, "Excel Files (*.xlsx)|Excel Macro Files (*.xlsm)", BitOR(1, 2), "") If @error Then Return 0 EndIf ;~ When an Excel file is selected, remember of the files location (path), file name, and file extension. $aPathSplit = _PathSplit($ChosenFileName, $sDrive, $sDir, $sFileName, $sExtension) ;~ Show me what file I selected in a Message Box. MsgBox(0, "Selected File", $sFileName) ;~ Display the chosen file name in the UI label (previously [No File Selected]) and make it green. GUICtrlSetData($FileName, "") $FileName = GUICtrlCreateLabel($sFileName, 104, 40) $FileName = GUICtrlSetColor($FileName, 0x32CD32) ;~ A file is now selected. The "Function" buttons are now enabled. Global $FileChosen = 1 GUICtrlSetState($CheckCourse, $GUI_ENABLE) GUICtrlSetState($DeleteCourse, $GUI_ENABLE) GUICtrlSetState($CopyCourse, $GUI_ENABLE) EndFunc ;==>_LocateGetFileName ;~ The user clicked the "Check Courses" button. This function will execute now. Func _CheckCourses() ;~ Disable the "Function" buttons again to prevent multiple processes. GUICtrlSetState($CheckCourse, $GUI_DISABLE) GUICtrlSetState($DeleteCourse, $GUI_DISABLE) GUICtrlSetState($CopyCourse, $GUI_DISABLE) ;~ Open a IE window and navigate to the login page. Global $oIE = _IECreate($urlBBLogin) ;~ Recognize the form on this page (login input boxes). Local $oForm = _IEFormGetObjByName($oIE, "login") Local $oTextLogin = _IEFormElementGetObjByName($oForm, "user_id") Local $oTextPass = _IEFormElementGetObjByName($oForm, "password") ;~ Enter the Automation user credentials into the form. _IEFormElementSetValue($oTextLogin, $bbUsername) _IEFormElementSetValue($oTextPass, $bbPassword) ;~ Click the Login button. _IEFormSubmit($oForm) ;~ Now that were logged in, navigate to the course search page. _IENavigate($oIE, $urlBBCourseSearch) ;~ Change the search criteria to "Course ID" _bbCourseSearchCategoryChange("Course ID") ;~ Open the selected Excel file Local $oAppl = _Excel_Open() Local $oWorkbook = _Excel_BookOpen($oAppl, $ChosenFileName, Default, Default, True) ;~ Copy just whats in cell A1 (for now) _Excel_RangeCopyPaste($oWorkbook.Worksheets(1), "A1") Global $WhatsCopied = ClipGet() ;~ Paste whats copied into the search text box and click submit Local $oForm = _IEGetObjByName($oIE, "courseManagerFormSearch") Local $oSearchString = _IEFormElementGetObjByName($oForm, "courseInfoSearchText") _IEFormElementSetValue($oSearchString, $WhatsCopied) _IEFormSubmit($oForm) ;~ Lets see what we got from the search Local $oBBTable = _IETableGetCollection($oIE, 2) Local $aBBTableData = _IETableWriteToArray($oBBTable) _ArrayDisplay($aBBTableData) EndFunc ;==>_CheckCourses ;~ This function allows changing the search criteria. Func _bbCourseSearchCategoryChange($sCategoryToSearch) Local $aSearchCategory[6] = ["Course ID", "Course Name", "Description", "Instructor", "Data Source Key", "Term"] Local $oForm = _IEGetObjByName($oIE, "courseManagerFormSearch") Local $oSearchCategory = _IEGetObjByName($oForm, "courseInfoSearchKeyString") _IEAction($oSearchCategory, "focus") _IEFormElementOptionSelect($oSearchCategory, $aSearchCategory[$sCategoryToSearch], 1, "byText") EndFunc ;==>_bbCourseSearchCategoryChange ;~ All exit commands, including F4, calls this function Func _Exit() Exit EndFunc ;==>_Exit  
      My main question is: How do I create an If... Then based on what is found in the search results? I need additional tasks to run if Col 1, Row 2 in the array contains the exact string I searched for. (Am I going about this the right way?)
      My next question (I might make a new thread for): How do I make the whole thing loop, as in, copy the next cell in the Excel sheet and do the whole thing over again until there's no more? I understand that a For/Next loop thingy would be used. I just don't know how. Loops are really confusing to me.
      Thank you all for your guidance and have a happy new year!
    • VADemon
      By VADemon
      I've encountered a problem with a single file where I cannot retrieve it's Date-time. So far my code has worked well for over 30 files, but this one is a mystery I cannot debug myself due to insufficient Au3 knowledge.
      In line 11 "_Date_Time_FileTimeToArray" is called and for this particular file it sets the @error to 10. I don't know what that error code means, but it's not set by the _Date functions themselves I think.
      Overall, it could be a problem caused by any of the functions below, how can I properly debug this? / Does anybody know a what's causing this?
      _WinAPI_CreateFile() / _Date_Time_GetFileTime() / _Date_Time_FileTimeToArray()
      Func _SetFileTimes($sFilePath) Local $monthNumber[13] = ["", "January", "February", "March", "April", "May", "Juny", "July", "August", "September", "October", "November", "December"] Local $dayNumber[7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] Local $fHandle = _WinAPI_CreateFile($sFilePath, 2, 2) ; read-only ; may NOT return a valid date for some reason! TODO Local $fTagFILETIME = _Date_Time_GetFileTime($fHandle) _WinAPI_CloseHandle($fHandle) ; This will return an empty array if theres no valid date $fModTime = _Date_Time_FileTimeToArray($fTagFILETIME[2]) ; last Modified if @error <> 10 then Local $year = $fModTime[2] Local $month = $fModTime[0] Local $day = $fModTime[1] Local $hour = $fModTime[3] Local $min = $fModTime[4] Local $sec = $fModTime[5] Local $ms = $fModTime[6] Local $weekday = $fModTime[7] Global $prettyTimestamp = StringFormat("%s, %s %d, %04d %02d:%02d:%02d", $dayNumber[$weekday], $monthNumber[$month], $day, $year, $hour, $min, $sec) Global $uploadDate = StringFormat("%04d-%02d-%02d", $year, $month, $day) $fModTime = _Date_Time_FileTimeToArray(_Date_Time_FileTimeToLocalFileTime($fTagFILETIME[2])) ; last Modified Local $year = $fModTime[2] Local $month = $fModTime[0] Local $day = $fModTime[1] Local $hour = $fModTime[3] Local $min = $fModTime[4] Local $sec = $fModTime[5] Local $ms = $fModTime[6] Local $weekday = $fModTime[7] ; GetUnixTime accounts for Local time, hence feed it local time Global $unixTimestamp = _GetUnixTime($year &"/"& $month &"/"& $day &" "& $hour&":"& $min &":"& $sec) else Global $prettyTimestamp = "N/A" Global $uploadDate = "" Global $unixTimestamp = "N/A" endif endfunc  
      _GetUnixTime returned the year 1601 start date, showing that $fModTime is probably equal 0. (But Why?)
      The file reports these dates in Explorer, it's on local NTFS drive:
      Created: ‎‎Wednesday, ‎31. ‎Januar ‎2018, ‏‎18:55:02
      Modified: ‎Wednesday, ‎10. ‎Januar ‎2018, ‏‎12:39:23
      Accessed: ‎Wednesday, ‎10. ‎Januar ‎2018, ‏‎12:39:23
    • nooneclose
      By nooneclose
      I need help turning this string "20180913221626" into a formatted time string.
      I need to go from this: 20180913221626
      to this: 09/13/2018 10:16 PM
      I do not always know what the date will be so I can not just use a variable I need to actually convert/format. 
      I did see an older post in the forms that was basically the same question only the other guy did not post the working code and I can not figure out how to use _AD_GetObjectProperties properly to get what I want. 
      As always any help would be appreciated. 
      Here is the code I use to find the date, but it always gives me the unformatted version. 
      ;retrieve the items object $oItem = $oOutlook.Session.GetItemFromID($aItems[1][0], Default) $oItem.GetInspector $eSentOn = $oItem.SentOn ; When was the email sent? MsgBox("", "Sent On of the email", $eSentOn) ;******************************************************************************* ; Formats the date and time from the email ;******************************************************************************* ;Local $fDatenTime = _DateTimeFormat($eSentOn, 1) ;MsgBox("", "Formatted email time", $fDatenTime) $aProperties = _AD_GetObjectProperties($eSentOn) _ArrayDisplay($aProperties, "Did the conversion work?")  
    • Miliardsto
      By Miliardsto
      I got that func
      Func makeHelpImgGUI($title,$width,$height,$img) $img = GUICtrlCreatePic("",20,40,$width,$height) _ResourceSetImageToCtrl($img, "HERE") EndFunc and I call this func like that
      makeHelpImgGUI("Image",1190, 800,$SETTINGS_JPG)  
      so what is the problem in the parameter where is - "HERE" I need value of img but passed as string
      so $img = $SETTINGS_JPG and how make it "SETTINGS_JPG"
      I tried something like that but not work
      Func makeHelpImgGUI($title,$width,$height,$img) $name_str = String($img) $name_str = StringTrimLeft ($name_str, 1 ) $img = GUICtrlCreatePic("",20,40,$width,$height) _ResourceSetImageToCtrl($img, $name_str) EndFunc  
    • liagason
      By liagason
      Hello everyone,
      How can I display in ascending  sequence some numbers stored in a string variable?
      $str = "18,03,48,23" MsgBox(0,"test",$str) I would like it to display "03,18,23,48"