Jump to content

How To Search And Replace Text In A File


Recommended Posts

I have about 100 text files that contain a particilular string that I need to replace. Simpleminded that I am, what I did was open a file, read each line, search the line for the string and replace it, write the revised line to another file until a new text file is built, then replace the old text file with the newly written one.

I'm almost sure this is taking the long way around so I was wondering if there is another way I can do it without going through all that process. I tried writing directly to the opened file but it would either only write at the end of the file or totally erase all content.

Thanks in advance to all.

Link to comment
Share on other sites

  • 2 years later...

$szFile = "c:\file.txt"

$szText = FileRead($szFile,FileGetSize($szFile))

$szText = StringReplace($szText, "replace me", "with me")

FileDelete($szFile)

FileWrite($szFile,$szText)

Lar.

Larry,

Sorry for the simple-minded question, but would you mind explaining the logic of the above script. It works great for what I'm using, but I can't figure out why it works. For example, the FileRead function

and the FileWrite functions work differently than I expected. I'm a little new at this.

Thanks in advance.

Link to comment
Share on other sites

Hi

Fileread reads the whole file into 1 string; [if you want only one line at a time use filereadLine from HelpFile]

after processing stringreplace

filewriteline writes the whole string back to the file.

Best, randall

[i agree with cyberslug; I would use a line to make a backup before processing]

Best, randall

Link to comment
Share on other sites

  • 4 months later...

:D:P:P Wowowowow. That's LIGHTNING fast!!!!! :D:shocked::shocked:

And is so simple too!

Thinking the minutes it takes to replace >1000 of strings with Notepad (I usually do that with MD5 files I have on a removable drive wich changes its drive letter when on other PC) I see that AutoIt is a blessing. :):D

Thank you, Larry for the code, I added a couple of InputBoxes to it if you don't mind:

$File=InputBox("Find and replace","Name and/or patch of the file",".md5","",500,100)
$FileContent=FileRead($File,FileGetSize($File))
$Find=InputBox("Find and replace","What to find?","FindThisText","",500,100)
$Replace=InputBox("Find and replace","What to write instead?","ReplaceWithThisText","",500,100)
$Confirm=MsgBox(65,"Find and replace","You are about to change every instance of "&$Find&" by "&$Replace&" in the file "<A href="mailto:&$File&@LF&"¿Are">&$File&@LF&"¿Are you sure?")
If $Confirm=1 Then
 $FileContent=StringReplace($FileContent,$Find,$Replace)
 FileDelete($File)
 FileWrite($File,$FileContent)
EndIf

I also added a confirmation question.

AutoIt is a blessing, I don't know how I was able to use my computer before [Auto]It :-S

Link to comment
Share on other sites

  • 3 weeks later...

:D:P:P Wowowowow. That's LIGHTNING fast!!!!! :D:shocked::shocked:

And is so simple too!

Thinking the minutes it takes to replace >1000 of strings with Notepad (I usually do that with MD5 files I have on a removable drive wich changes its drive letter when on other PC) I see that AutoIt is a blessing. :):D

Thank you, Larry for the code, I added a couple of InputBoxes to it if you don't mind:

$File=InputBox("Find and replace","Name and/or patch of the file",".md5","",500,100)
$FileContent=FileRead($File,FileGetSize($File))
$Find=InputBox("Find and replace","What to find?","FindThisText","",500,100)
$Replace=InputBox("Find and replace","What to write instead?","ReplaceWithThisText","",500,100)
$Confirm=MsgBox(65,"Find and replace","You are about to change every instance of "&$Find&" by "&$Replace&" in the file "<A href="mailto:&$File&@LF&"¿Are">&$File&@LF&"¿Are you sure?")
If $Confirm=1 Then
 $FileContent=StringReplace($FileContent,$Find,$Replace)
 FileDelete($File)
 FileWrite($File,$FileContent)
EndIf

I also added a confirmation question.

Will this allow me to select multiple files to process at one time?

Edited by Automan Empire
"I've seen your work in the past, and it's novice at best..." SmOke_N
Link to comment
Share on other sites

  • 4 years later...

You can search a topic which was started 7 years ago but you don't know about _FileListToArray() & _ReplaceStringInFile(), please.

Next time instead of resurrecting an old thread, first consider searching a little deeper and then start a new topic if you're truly stuck.

DO NOT REPLY.

Edited by guinness

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

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