leuce Posted December 1, 2012 Posted December 1, 2012 (edited) G'day everyone I'm writing a script that will move files on my hard drive. In 99% of cases, there will not be a file in the target directory with the same name as the file that I'm moving towards that directory, but in 1% of cases, there will be an existing file in that directory with the same name. Instead of either skipping the file or replacing it, I would like to rename it with a number. Is that easily done? I can easily rename the file using a date/time stamp (_NowCalc), or with a random number, but it will look more elegant if I can simply rename it with a single digit, that increments by 1 every time the same file name is being copied again. It doesn't matter to me which file is renamed -- the existing file or the file that I'm moving -- as long as it becomes possible for both files to be in the same directory with highly similar names. For example, if I move "file.txt" to a folder and "file.txt" already exists, I'd like to rename one of them to "file1.txt", and the next time I try to move another "file.txt" to that folder, I'd like to rename one of them "file2.txt", etc. Tis a pity FileExists doesn't take regex :-) Added: I'm trying to see if I can use _FileListToArray for this, but _FileListToArray only supports wildcards within the actual file name, and in my script the file name is a variable. How does one combine variables with wildcards? For example, if $filename1stpart is "foo" and $filename2ndpart is "bar", how can I specify "foo*bar" in _FileListToArray? Thanks Samuel Edited December 1, 2012 by leuce
water Posted December 1, 2012 Posted December 1, 2012 You need something like this. I use FileCopy for easier testing. Replace it with FileMove if it works for you. #include <File.au3> Global $sFileFrom = "C:temptest.txt" Global $sFileTo = "C:temptest.txt" $vResult = _SecureFileMove($sFileFrom, $sFileTo) If $vResult == 0 Then ; 0 = error MsgBox(0, "", "Error moving file to: " & $sFileTo) Else ; on success the name of the moved file is returned MsgBox(0, "", "File successfully moved to: " & $vResult) EndIf Exit Func _SecureFileMove($sFileFrom, $sFileTo) Local $iIndex = 0, $sFileTemp, $iResult Local $sDrive, $sDir, $sFName, $sExt If FileExists($sFileTo) Then _PathSplit($sFileTo, $sDrive, $sDir, $sFName, $sExt) While 1 $iIndex = $iIndex + 1 $sFileTemp = $sDrive & $sDir & $sFName & "_" & $iIndex & $sExt If Not FileExists($sFileTemp) Then ExitLoop WEnd $sFileTo = $sFileTemp EndIf $iResult = FileCopy($sFileFrom, $sFileTo) If $iResult = 1 Then Return $sFileTo Return 0 EndFunc ;==>_SecureFileMove UritOR 1 My UDFs and Tutorials: Spoiler UDFs: Active Directory (NEW 2024-07-28 - Version 1.6.3.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 (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
guinness Posted December 1, 2012 Posted December 1, 2012 Or if you use WinAPIEx then >> _WinAPI_PathYetAnotherMakeUniqueName 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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018
Chance Posted December 1, 2012 Posted December 1, 2012 (edited) Here's how I'd generate a new name for an existing file. I just made this for an example I guess, I haven't tested much and am unsure of bugs that might exist under certain circumstances. rename it with a single digit, that increments by 1 every time the same file name is being copied again. But if you want to do that, you have to edit this code to check for that string, possibly using regular expression like regexpreplace, should be very simple. how can I specify "foo*bar" in _FileListToArray? I have no experience with that function so I wouldn't know either :/ Global $Result = _UniqueName(@AutoItExe) ConsoleWrite("File : " & $Result & @CR) $Result = _UniqueName(@SystemDir) ConsoleWrite("Directory : " & $Result & @CR) Func _UniqueName($FilePath) If FileExists($FilePath) Then Local $Split = StringSplit($FilePath, "") $FileName = $Split[$Split[0]] Local $Path For $I = 1 To $Split[0] - 1 $Path &= $Split[$I] & "" Next If StringInStr($FileName, ".", 2) Then $FileName = StringReplace($FileName, ".", "(%s)." , -1);If you have a file like "C:testname.with.many.dots.txt", it will be renamed to "C:testname.with.many.dots(1).txt" if the file existed.. Local $TempName For $I = 1 To 10e+100 $TempName = StringFormat($FileName, $I) If Not FileExists($Path & $TempName) Then ExitLoop Next $FilePath = $Path & $TempName Else $FileName &= "(%s)" Local $TempName For $I = 1 To 10e+100 $TempName = StringFormat($FileName, $I) If Not FileExists($Path & $TempName) Then ExitLoop Next $FilePath = $Path & $TempName EndIf EndIf Return $FilePath EndFunc Edit: stupid tag formatting... Edit2: OMG WHY DOES THE FORUM KEEP FORMATTING CODE IN AUTOIT TAGS D:< Edited December 1, 2012 by FlutterShy
leuce Posted December 1, 2012 Author Posted December 1, 2012 Thanks, everyone, for your ideas. The solution I used is the While loop in It was simple enough to borrow and rework for my purposes. Thanks again.
water Posted December 1, 2012 Posted December 1, 2012 I'm glad we could help to solve your problem My UDFs and Tutorials: Spoiler UDFs: Active Directory (NEW 2024-07-28 - Version 1.6.3.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 (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
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now