Jump to content

Replace String in multiple files.


Recommended Posts

  • Moderators

@jswilcox1980 no offense, but you have received a lot of assistance from several forum members, and are not putting much forward beyond "nope, not working"....

"/c closes most but not all" - How about an example of one (or several) it doesn't close, so we can help you figure out your code?

"and its still hanging up not renaming the folders" - How about we tackle one problem at a time. Feel free to try different things on your own, based on our suggestions...

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

@Jlogan3o13 I understand  your concerns, i am a computer guy not a programmer however i can usually look at code and figure out what things are happening.  I will and have been trying multiple things, i am more than appreciative of all of your help, i have helped on forums of different topics, obviously not programming.  I will try to be more clear.

@visciousXUSMC  i have attached a quick screen shot of the folder structure,  Again thank you all for your help.

folderstructure.PNG

Also the file folders typically would be named the same....for this testing purposes it shouldnt matter, i just used one set of folders/files and made multiple copies of them.

 

 

Edited by jswilcox1980
Link to comment
Share on other sites

Id imagine your having the same issue I had when I was looping files & folders at the same time, if that parent folder changes its name before the sub folder then the paths will be wrong for the rest of the per-determined array.

The solution would be to make sure not to have a folder more than one directory deep or create a more advanced array that always goes to the deepest level first and works its way up.

Link to comment
Share on other sites

Id imagine your having the same issue I had when I was looping files & folders at the same time, if that parent folder changes its name before the sub folder then the paths will be wrong for the rest of the per-determined array.

The solution would be to make sure not to have a folder more than one directory deep or create a more advanced array that always goes to the deepest level first and works its way up.

thanks looks like i have more tinkering to do then, Thank  you for all of your help... the issue with not "all" the CMD prompt windows closing was an error on my part (fat fingers).  I actually thought this would be easier than it is lol, guess thats why im not a software programmer!   Lupas Rename 2000 does this in about 5 seconds selecting use folders as files and using recursive mode.....just a few clicks and its done but wanted to have a one stop shop solution.  im not giving up ...just need to learn some more i suppose!

Link to comment
Share on other sites

I came up with an idea, I have no idea how good it is or how inefficient it is so one of the better coders can maybe give you an alternative but my idea is since "\" cant be used as part of the folder name and each level the folder is deeper will put another "\" in the file path.  I check in a reverse loop for how many times the character "\" shows up in the string and if it matches the loop iteration it gets processed. 

I tried it on some test folders and somehow one of them did not get renamed the first pass so I guess my idea is not perfect.

#Include <File.au3>

Local $sDirectory = @ScriptDir & "\Test"
Local $aFiles = _FileListToArrayRec($sDirectory, "*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH)
Local $aFilesName = _FileListToArrayRec($sDirectory, "*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_NOPATH)
Local $aFolders = _FileListToArrayRec($sDirectory, "*", $FLTAR_FOLDERS, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH)
Local $aFoldersName = _FileListToArrayRec($sDirectory, "*", $FLTAR_FOLDERS, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_NOPATH)

If IsArray($aFiles) Then
For $i = 1 to $aFiles[0]
    If StringRegExp($aFiles[$i],".*?_000(.3sz|.ini)?$") Then
        Run(@ComSpec & " /c REN " & '"' & $aFiles[$i] & '" "' & StringRegExpReplace($aFilesName[$i],   "_000(.3sz|.ini)?$", "$1") & '"')
    EndIf
Next
EndIf


For $i2 = 30 to 1 Step -1
For $i = 1 to $aFolders[0]
    If _CountStr($aFolders[$i], "\") = $i2 Then
    If StringRegExp($aFolders[$i],".*?_000(.3sz|.ini)?$") Then
        Run(@ComSpec & " /c REN " & '"' & $aFolders[$i] & '" "' & StringRegExpReplace($aFoldersName[$i],   "_000(.3sz|.ini)?$", "$1") & '"')
    EndIf
    EndIf
Next
Next

Func _CountStr($sStr, $sFind)
    StringReplace($sStr, $sFind, $sFind)
    Return @Extended
EndFunc

Edit figured out why that did not work, it was simply too fast!  Adding Sleep(100) to the loop fixed it.  However I built another method before figuring that out, this seems more advanced, from a performance standpoint not sure if it is better or worse.  One of the other guys can chime in on that matter.  I still have not implemented Guinesses idea yet since I have not tested it to see how it works, I am not sure what @Extended returns on a replace and what happens if it does not continue the loop.

Here is what I came up with this morning to handle the directory issue:

 

#Include <File.au3>
#Include <Array.au3>

Local $sDirectory = @ScriptDir & "\Test"
Local $aFiles = _FileListToArrayRec($sDirectory, "*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH)
Local $aFilesName = _FileListToArrayRec($sDirectory, "*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_NOPATH)
Local $aFolders = _FileListToArrayRec($sDirectory, "*", $FLTAR_FOLDERS, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH)
Local $aFoldersName = _FileListToArrayRec($sDirectory, "*", $FLTAR_FOLDERS, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_NOPATH)

;Check if there are files and if exist rename based on regex
If IsArray($aFiles) Then
For $i = 1 to $aFiles[0]
    If StringRegExp($aFiles[$i],".*?_000(.3sz|.ini)?$") Then
        Run(@ComSpec & " /k REN " & '"' & $aFiles[$i] & '" "' & StringRegExpReplace($aFilesName[$i],   "_000(.3sz|.ini)?$", "$1") & '"')
    EndIf
Next
EndIf

;Add two colums and then add the folder name and directory count to the new colums, then sort by deepest directory first.
If IsArray($aFolders) Then
$aFolders = _ArrayAdd_Column($aFolders)
$aFolders = _ArrayAdd_Column($aFolders)
For $i = 0 to $aFolders[0][0]
    $aFolders[$i][2] = _CountStr($aFolders[$i][0], "\")
    $aFolders[$i][1] = $aFoldersName[$i]
Next
_ArraySort($aFolders, 1, Default, Default, 2)

_ArrayDisplay($aFolders)

;Rename Folders Based on RegEx
For $i = 0 to UBound($aFolders) -1
    If StringRegExp($aFolders[$i][0],".*?_000(.3sz|.ini)?$") Then
        Run(@ComSpec & " /c REN " & '"' & $aFolders[$i][0] & '" "' & StringRegExpReplace($aFolders[$i][1],   "_000(.3sz|.ini)?$", "$1") & '"')
        Sleep(100)
    EndIf
Next
EndIf
;*******Functions*****

Func _ArrayAdd_Column($Array)
    Local $aTemp[UBound($Array)][UBound($Array, 0) + 1]
    For $i = 0 To UBound($Array) - 1

        For $j = 0 To UBound($Array, 0) - 1
            If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
            If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
        Next
    Next
    Return $aTemp
EndFunc  ;==>_ArrayAdd_Column

Func _CountStr($sStr, $sFind)
    StringReplace($sStr, $sFind, $sFind)
    Return @Extended
EndFunc

 

Edited by ViciousXUSMC
Link to comment
Share on other sites

So you want me to code it for you? Well I will give you a clue...

Local $sTemp = Null
For $i = 1 to $aFiles[0]
    $sTemp = StringRegExpReplace($aFilesName[$i],   "_000(.3sz|.ini)?$", "$1")
    If Not @extended Then ContinueLoop ; Skip replacement if nothing was replaced i.e. @extended == 0

    Run(@ComSpec & " /k REN " & '"' & $aFiles[$i] & '" "' & $sTemp & '"')
Next

 

@guinness Just tested this, works great.  I debugged so I could see what is happening.

So on replace @Extended is a number other than 0, on not replace its a 0.
The If statement is saying if NOT @Extended (Not 0) ContinueLoop - that moves it to the next line where the @ComSpec runs (I get this)

Where I get stuck is why if the If statement is not true it does not just continue onto the next line anyways, with any other if statements it would simply just not carry out the "Then" portion but move onto the next line of code. 

$a = 1
If $a = 0 Then MsgBox(0, "", "True if You See Me")
If $a = 1 Then MsgBox(0, "", "@ComSpec Rename Code Stuff")

The way I am familiar with this working would be to enclose the If statement with an EndIf so that the next line is only performed if the statement is true. 

I am assuming the above example is a special case when in a loop that the code looks into the If statement even if its false and sees ContinueLoop and knows to start the loop over on the next iteration because the statement was false? 
 

Edited by ViciousXUSMC
Link to comment
Share on other sites

@extended is the number of replacements and continue loop navigates back to the top of the loop, skipping everything below it. If Not is used when a value is falsey e.g. 0, empty string etc... so Not @extended is saying Not True or @extended = 0. Understand?

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

It should have been called ContinueBackToTheTopOfTheLoopWhereTheForOrDoOrWhileIs, but it's too late now. Where were you 10 years ago? =)

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

This is all working as i need it to Thanks again,   My only question is  i have been looking at the @SW_HIDE command to make it not show the command windows popping up... I have tried placing it in multiple places in the @Comspec ines, unsuccessfully. 

#Include <File.au3>
;All code provided by VisciousXUSMC on www.autoitscript.com

Local $sDirectory = @ScriptDir & "\Test"
Local $aFiles = _FileListToArrayRec($sDirectory, "*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH)
Local $aFilesName = _FileListToArrayRec($sDirectory, "*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_NOPATH)
Local $aFolders = _FileListToArrayRec($sDirectory, "*", $FLTAR_FOLDERS, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH)
Local $aFoldersName = _FileListToArrayRec($sDirectory, "*", $FLTAR_FOLDERS, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_NOPATH)

If IsArray($aFiles) Then
For $i = 1 to $aFiles[0]
    If StringRegExp($aFiles[$i],".*?_000(.3sz|.ini)?$") Then
        Sleep(1000)
        Run(@ComSpec & " /c REN " & '"' & $aFiles[$i] & '" "' & StringRegExpReplace($aFilesName[$i],   "_000(.3sz|.ini)?$", "$1") & '"')
    EndIf
Next
EndIf


For $i2 = 30 to 1 Step -1
For $i = 1 to $aFolders[0]
    If _CountStr($aFolders[$i], "\") = $i2 Then

    If StringRegExp($aFolders[$i],".*?_000(.3sz|.ini)?$") Then
        sleep(1000)
        Run(@ComSpec & " /c REN " & '"' & $aFolders[$i] & '" "' & StringRegExpReplace($aFoldersName[$i],   "_000(.3sz|.ini)?$", "$1") & '"')

    EndIf

    EndIf

    Next
Next

Func _CountStr($sStr, $sFind)
    StringReplace($sStr, $sFind, $sFind)
    Return @Extended
EndFunc

;This section of code Replaces the PCID specified by the user

Local $sDirectory = @ScriptDir & "\test"
Local $aFiles = _FileListToArrayRec($sDirectory, "*.ini", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH)
Local $sChange = InputBox("Update All .INI Files In " & $sDirectory, "Enter New PCID","204256", "", @DesktopWidth/6)

For $i =1 to $aFiles[0]
    IniWrite($aFiles[$i], "INFO", "PCID",$sChange)
Next

MsgBox(48, "Process Completed!!!", "All .Ini Files and Folders Updated!")

 

Link to comment
Share on other sites

@SW_HIDE needs to be passed as parameter 3 so the statement should look like:

Run(@ComSpec & " /c REN " & '"' & $aFiles[$i] & '" "' & StringRegExpReplace($aFilesName[$i], "_000(.3sz|.ini)?$", "$1") & '"', "", @SW_HIDE)

 

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

You can probably lower that sleep amount pretty safely.  It worked for me at Sleep(100) 

I am still not sure what method of the two I put above is best, id imagine the 2nd since it is not running the loop over and over 30 times :) but unless your working with a HUGE amount of stuff you may not notice any difference.  I just like to try to learn some best practices and better coding as I go from the pros around here.

Link to comment
Share on other sites

You can probably lower that sleep amount pretty safely.  It worked for me at Sleep(100) 

I am still not sure what method of the two I put above is best, id imagine the 2nd since it is not running the loop over and over 30 times :) but unless your working with a HUGE amount of stuff you may not notice any difference.  I just like to try to learn some best practices and better coding as I go from the pros around here.

with my POS work laptop with Sleep(100) it was missing a second level folder once or twice.  Not sure why but when i upped it to 1000 its fine.  Speed isnt critical when it might take 30 seconds at most to complete everything.  at most the customers using this might only be processing 15 sets of folders, again not a huge deal.  Thanks for your support, I really do appreciate it!

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