Sign in to follow this  
Followers 0
leuce

When moving files, and a file already exists, add a number to it's name

7 posts in this topic

#1 ·  Posted (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 by leuce

Share this post


Link to post
Share on other sites



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
1 person likes this

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

Or if you use WinAPIEx then >> _WinAPI_PathYetAnotherMakeUniqueName


_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)

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 by FlutterShy

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

I'm glad we could help to solve your problem :D


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

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