Sign in to follow this  
Followers 0
Sam137

Find & Replace with little tweaks

13 posts in this topic

Hello

I have a typical requirement.

I have a folder which contains n number of files. I have a partial search string with me and i do have a full replace string also with me.

Suppose consider the file contains:

***************************

filepath = c:\test\search.in

logpath = c:\test\search.in

***************************

1. The code is to first search for "filepath =" and it should extract the full sentence "filepath = c:\test\search.in" and do a replace with the string "filepath = d:\user\search.in".

2. Next the code is to search for "logpath =" and it should extract the full sentence "logpath = c:\test\search.in" and do a replace with the string "logpath = d:\user\search.in".

Like this i have to do in all the files which i have in the folder.

Is this possible using Autoit?

Share this post


Link to post
Share on other sites



Of course it is possible.

What you need is:

FileFindFirstFile

FileFindNextFile

You will get all the files in the folder.

For every file, you can use _ReplaceStringInFile to replace the strings.

Have a look at the examples in the help file and you'll be able to build the script.


SNMP_UDF ... for SNMPv1 and v2c so far, GetBulk and a new example script

wannabe "Unbeatable" Tic-Tac-Toe

Paper-Scissor-Rock ... try to beat it anyway :)

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

As I stated before, look at _FileListToArray(), but instead of _ReplaceStringInFile look at the INI functions.

Edited by guinness

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

$sStr = StringRegExpReplace($sStr, "(?m:^)(?i).+?=)©(:.+)", "$1d$2")

Edit: The copyright symbol is supposed to be "(" followed by "c" followed by")" >> no quotes

The forum code messed it up.

Edited by GEOSoft

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Share this post


Link to post
Share on other sites

OOps - I forgot about _FileListToArray :D good catch guinness


SNMP_UDF ... for SNMPv1 and v2c so far, GetBulk and a new example script

wannabe "Unbeatable" Tic-Tac-Toe

Paper-Scissor-Rock ... try to beat it anyway :)

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Try this.

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

Local $sNewStr
Local $sReplaceStr = "d:\user\search.in"

Local $var = FileSelectFolder("Choose a folder.", "c:", 7, @ScriptDir & "\")
If @error Then Exit

Local $FileList = _FileListToArray($var, "*.in?")
If @error Then Exit

_ArrayDisplay($FileList, "$FileList")

For $i = 1 To UBound($FileList) - 1
    $sStr = FileRead($var & "\" & $FileList[$i])
    If StringRegExp($sStr, "(?im)^(filepath|logpath\h*=\h*[^\v]+)") Then
        $sNewStr = StringRegExpReplace($sStr, "(?im)^(filepath|logpath)(\h*=\h*)([^\v]+)", "$1$2" & _
                StringRegExpReplace($sReplaceStr, "(\\)", "\\\\"))
        ;ConsoleWrite("======== Contents of " & $var & "\" & $FileList[$i] & " ========" & @LF)
        ;ConsoleWrite($sNewStr & @LF)
        ;ConsoleWrite("========================================================================" & @LF)
        $file = FileOpen($var & "\" & $FileList[$i],2)
        FileWrite($file,$sNewStr)
        FileClose($file)
        ShellExecute('notepad.exe', $var & "\" & $FileList[$i]) ; View actual file
    EndIf
Next

Edit: Changed ShellExecute() to open file with notepad, because a file with the extension ".in" most likely does not have a default application to use.

Edit2: Added full path of file to FileOpen function as per GEOSoft post #13,

Edited by Malkey

Share this post


Link to post
Share on other sites

Thanks so much for the quick turnaround. I tried the above coding and its not replacing the striing as per the requirement. Moreover i could not understand

$sNewStr = StringRegExpReplace($sStr, "(?im)^(filepath|logpath)(h*=h*)([^v]+)", "$1$2" & _
                StringRegExpReplace($sReplaceStr, "()", ""))
I went through the help file for the function StringRegExpReplace. It will be good can anyone help where i am going wrong.

Share this post


Link to post
Share on other sites

I added some message boxes for the fileread, its returning spaces. And then i realized that i am going wrong(not sure) so added Fileopen, its returning 1 but the fileread is returning spaces....

For $i = 1 To UBound($FileList) - 1
$open = FileOpen($FileList[$i],2)
msgbox(0,"",$open)
    $sStr = FileRead($FileList[$i])
msgbox(0,"",$sStr)
    If StringRegExp($sStr, "(?im)^(filepath|logpathh*=h*[^v]+)") Then
        $sNewStr = StringRegExpReplace($sStr, "(?im)^(filepath|logpath)(h*=h*)([^v]+)", "$1$2" & _
                StringRegExpReplace($sReplaceStr, "()", ""))
        ;ConsoleWrite("======== Contents of " & $var & "" & $FileList[$i] & " ========" & @LF)
        ;ConsoleWrite($sNewStr & @LF)
        ;ConsoleWrite("========================================================================" & @LF)
  msgbox(0,"",$sNewStr)
        $file = FileOpen($FileList[$i],2)
        FileWrite($file,$sNewStr)
        FileClose($file)
        ShellExecute($FileList[$i]) ; View actual file
    EndIf
Next

Share this post


Link to post
Share on other sites

You don't need to use fileopen for a simple fileread()

Put a #Include<array.au3> Line at the top of your script.

after the file array is created add the line

_ArrayDisplay($FileList)

You are probably not getting the full path returned in the array and that will cause an issue with FileRead()


George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Share this post


Link to post
Share on other sites

The code which i given is only a part. I have already used that and for me arraydisplay works perfect.

#include <File.au3>
#include <Array.au3>
Local $sNewStr
Local $sReplaceStr = "d:usersearch.in"
Local $var = FileSelectFolder("Choose a folder.", "c:", 7, @ScriptDir & "")
If @error Then Exit
Local $FileList = _FileListToArray($var, "*.in?")
If @error Then Exit
;_ArrayDisplay($FileList, "$FileList")
For $i = 1 To UBound($FileList) - 1
$open = FileOpen($FileList[$i],2)
msgbox(0,"",$open)
    $sStr = FileRead($FileList[$i])
msgbox(0,"",$sStr)
    If StringRegExp($sStr, "(?im)^(filepath|logpathh*=h*[^v]+)") Then
        $sNewStr = StringRegExpReplace($sStr, "(?im)^(filepath|logpath)(h*=h*)([^v]+)", "$1$2" & _
                StringRegExpReplace($sReplaceStr, "()", ""))
        ;ConsoleWrite("======== Contents of " & $var & "" & $FileList[$i] & " ========" & @LF)
        ;ConsoleWrite($sNewStr & @LF)
        ;ConsoleWrite("========================================================================" & @LF)
  msgbox(0,"",$sNewStr)
        $file = FileOpen($FileList[$i],2)
        FileWrite($file,$sNewStr)
        FileClose($file)
        ShellExecute($FileList[$i]) ; View actual file
    EndIf
Next

Share this post


Link to post
Share on other sites

it might be displaying just fine but does each element contain the full path or just the file name?


George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Share this post


Link to post
Share on other sites

It just contains only the file name as search.in

Share this post


Link to post
Share on other sites

Then in order for you to use that filename you wile have to preceed it with the rest of the path.


George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

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  
Followers 0