Jump to content

Renaming a file without opening it


Chimaera
 Share

Recommended Posts

Im at a list on how to do this

I have a file that has unwanted charaters in it and i want to edit the filename without opening the file

I cant think of what the hell to use for this?

I think filemove will help but how do i selectively remove the unwanted characters

This is an example name

This.Is.My.filename.x666-Test.nzb

I need to remove " . - " and replace them with a space instead

But it cant remove the normal full stop before the nzb

Like this

This Is My filename x666 Test.nzb

I cant think of a FileOpen Dialog type of select to target the file without opening it

Link to comment
Share on other sites

This can be simplified, but for the purposes of using 99.99% AutoIt native functions, here >>

Local $sFilePath = 'C:This.Is.My.filename.x666-Test.nzb'
Local $sExtensionDot = StringInStr($sFilePath, '.', 2, -1) - 1
Local $sFileString = StringLeft($sFilePath, $sExtensionDot)
Local $sFileExtension = StringTrimLeft($sFilePath, $sExtensionDot)

ConsoleWrite('String: ' & $sFileString & @CRLF)
ConsoleWrite('Extension: ' & $sFileExtension & @CRLF)

Local $sFilePath_New = StringRegExpReplace($sFileString, '[.-]', ' ')  & $sFileExtension
ConsoleWrite('NewPath: ' & $sFilePath_New & @CRLF)
; FileMove($sFilePath, $sFilePath_New)
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

Might fit for your particular filename:

$sFile = @ScriptDir & "This.Is.My.filename.x666-Test.nzb"
$sNew = StringRegExpReplace($sFile, "(.*).*", "$1") & StringRegExpReplace(StringTrimRight(StringRegExpReplace($sFile, ".*(.*)", "$1"), 4), "(W+)", " ") & StringRight($sFile, 4)
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $sNew = ' & $sNew & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console
;~ FileMove($sFile, $sNew)

Br,

UEZ

Edited by UEZ

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Link to comment
Share on other sites

Thx guys i realised im not looking at the bigger picture it needs to be only letter [upper and lower] and numbers allowed.

I assumed it was only those 2 but in hindsight it could be other ones as well

Thanks for chipping in and sorry for not giving correct info

Link to comment
Share on other sites

  • Moderators

Chimaera,

Or like this: ;)

$sName = "This.Is.My.filename.x666-Test.nzb"

$sNew_Name = StringRegExpReplace($sName, "(?i)(-|.(?!nzb))", " ")

MsgBox(0, "Result", $sNew_Name)

SRE decode:

(?i)      - case insensitive (for the nzb bit)
(         - look for either
-         - dashes
|         - or
.(?!nzb) - a dot not followed by "nzb"
)         -

And replace with space.

M23

Edit: Just seen your post above - so this is obviously not the solution. :(

Edited by Melba23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Ok well i have got this far but ive lost the plot here somewhere.

Its supposed to read all the files in the folder then apply the change to them.

I know the regex is wrong because of the earlier fault but it should still work..

#region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_res_requestedExecutionLevel=requireAdministrator
#endregion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs ----------------------------------------------------------------------------
    AutoIt Version: 3.3.8.0
    Author:      Chimaera
    Script Function: NZB File Renamer
#ce ----------------------------------------------------------------------------
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <File.au3>
; ------------------------------------------------------------------------------
#RequireAdmin
; ------------------------------------------------------------------------------
#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7

Global $button1, $button2, $sNew_Name
Local $GUI_Start = GUICreate(" NZB File Renamer ", 250, 250, -1, -1, BitXOR($GUI_SS_DEFAULT_GUI, $WS_MINIMIZEBOX))

;~ $button1 = GUICtrlCreateButton(" Choose File ", 20, 50, 130, 35)
;~ GUICtrlSetFont(-1, 11, 550, -1, "Tahoma")
$button2 = GUICtrlCreateButton(" Change File ", 20, 100, 130, 35)
GUICtrlSetFont(-1, 11, 550, -1, "Tahoma")
GUISetState()

Local $nMsg = 0
While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
;~         Case $button1
;~             Local $sNzbFile = FileOpenDialog("Choose File", @ScriptDir, " NZB (*.nzb)", 4)
;~             ConsoleWrite($sNzbFile & @CRLF)
;~             If @error Then MsgBox(4096, "", "No File(s) chosen")
        Case $button2
            _NzbRename()
            MsgBox(4096, "", " File Name(s) Were Changed ")
    EndSwitch
WEnd

Func _NzbRename()
    Local $sNzbString = _FileListToArray( @ScriptDir, "*.nzb", 1)
    Local $aNzbList = StringSplit($sNzbString, "|")
;~         _ArrayDisplay( $aNzbList)
    For $i = 1 To $aNzbList[0]
        If @error = 0 Then
                $sNew_Name = StringRegExpReplace($sNzbFile, "(?i)(-|.(?!nzb))", " ")
                FileMove(@ScriptDir & "" & $sNzbFile, $sNew_Name, 1)
            Sleep(100)
        EndIf
    Next
EndFunc   ;==> _NzbRename()
Link to comment
Share on other sites

Could you provide a before and after of what you expect. Multiple examples would help.

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

Could you provide a before and after of what you expect. Multiple examples would help.

Ok ill try again

Origanal filename like this

This.Is.My.filename.x666-Test.nzb

But needs to be only Letters (lower and Upper case) and numbers

New name should be like this

This Is My filename x666 Test.nzb

Which should be done with this

Func _NzbRename()
Local $sNzbString = _FileListToArray( @ScriptDir, "*.nzb", 1) ; read all the .nzb into array
Local $aNzbList = StringSplit($sNzbString, "|") ; split them into seperate
;~ _ArrayDisplay( $aNzbList)
For $i = 1 To $aNzbList[0]
If @error = 0 Then
$sNew_Name = StringRegExpReplace($sNzbList[$i], "(?i)(-|.(?!nzb))", " ") ; Perform the regex on each file
FileMove(@ScriptDir & "" & $sNzbFile, $sNew_Name, 1) ; use file move to make the change in the files, old name to new name
Sleep(100)
EndIf
Next
EndFunc ;==> _NzbRename()

Its my fault ive confused you because i started off with the wrong assumptions in the first place

Link to comment
Share on other sites

chimaera,

This is wrong

Func _NzbRename()
    Local $sNzbString = _FileListToArray( @ScriptDir, "*.nzb", 1)
    Local $aNzbList = StringSplit($sNzbString, "|")
;~         _ArrayDisplay( $aNzbList)
    For $i = 1 To $aNzbList[0]
        If @error = 0 Then
                $sNew_Name = StringRegExpReplace($sNzbFile, "(?i)(-|.(?!nzb))", " ")
                FileMove(@ScriptDir & "" & $sNzbFile, $sNew_Name, 1)
            Sleep(100)
        EndIf
    Next
EndFunc   ;==> _NzbRename()

filelisttoarray returns an array.

Try this (not tested)

Func _NzbRename()
    Local $sNzblist = _FileListToArray( @ScriptDir, "*.nzb", 1)
;~         _ArrayDisplay( $aNzbList)
    For $i = 1 To $aNzbList[0]
        If @error = 0 Then
                $sNew_Name = StringRegExpReplace($sNzblist[$i], "(?i)(-|.(?!nzb))", " ")
                FileMove(@ScriptDir & "" & $sNzblist[$i], $sNew_Name, 1)
            Sleep(100)
        EndIf
    Next
EndFunc   ;==> _NzbRename()Func _NzbRename()

Also, if you want to change all non-word chars to psaces you might try this pattern (?i)(W(?!nzb))

kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

With a bit of fooling around this works

Func _NzbRename()
    $aNzbList = _FileListToArray(@ScriptDir, "*.nzb", 1)
;~       _ArrayDisplay( $aNzbList)
    For $i = 1 To $aNzbList[0]
        $sNew_Name = StringRegExpReplace($aNzbList[$i], "(?i)(W(?!nzb))", " ")
        FileMove(@ScriptDir & "" & $aNzbList[$i], $sNew_Name, 1)
        Sleep(100)
    Next
EndFunc   ;==>_NzbRename

The only thing i have noticed is if the filename has a". " ie a fullstop with a space straight after you end up with a double space.

But thats minor in the scheme of things

Thanks for all the help guys

Link to comment
Share on other sites

Thx guys i realised im not looking at the bigger picture it needs to be only letter [upper and lower] and numbers allowed.

I assumed it was only those 2 but in hindsight it could be other ones as well

Thanks for chipping in and sorry for not giving correct info

Just in case "-" and "." are not the only two characters that need to be replaced with a space.

$sName = "This.Is.My?filename.x666-Test.nzb"

$sNew_Name = StringRegExpReplace($sName, "([^A-Za-z0-9.]|.(?!w{3,4}$))", " ") ; Assuming any 3 or 4 "word" character file extension.

$sNew_Name2 = StringRegExpReplace($sName, "(?i)([^a-z0-9.]|.(?!nzb))", " ") ; Use if specific "nzb" file extension required.

MsgBox(0, "Result", $sNew_Name & @CRLF & $sNew_Name2, 6)
Link to comment
Share on other sites

Strip out the double WS with StringStripWS after the RegExp.

Like this you mean

StringStripWS( $aNzbList[$i], 4)

but that removes the double space completly does it not?

I need to still have 1 space between not 2.

Without going into too much detail

How is it you and Malkey have done two different setups for the regex for the same task?

Yours

(?i)(W(?!nzb))

Malkey

(?i)([^a-z0-9.]|.(?!nzb))
Edited by Chimaera
Link to comment
Share on other sites

  • Moderators

Chimaera,

SRE decode:

W      - match any non-word (a-z, A-Z, 0-9 or underscore)
(?!nzb)   - not followed by "nzb"

[^a-z0-9.] - match anything which is not (becasue of leading ^) alphanumeric or a dot
|        - or
.(?!nzb))  - a dot not followed by "nzb"

All clear? :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Moderators

Chimaera,

Go read that Help file: :D

(?i) : Case-insensitivity flag. [...] It tells the regex engine to do case-insensitive matching from that point on.

So when used with "a-z" it covers both lower- and upper-case characters. ;)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Like this you mean

StringStripWS( $aNzbList[$i], 4)

but that removes the double space completly does it not?

I need to still have 1 space between not 2.

Try it and see.


Another thing that I would do is remove the file extension before the regexp and add it again after (this will simplify the regexp). Then you will not be limited to a particular file type, and (more importantly) you won't encounter problems in cases where the extension appears elsewhere in the file name. Of course there are other methods to achieve the same results, but this is easier to implement than using a single complicated regexp.

Edited by czardas
Link to comment
Share on other sites

Thanks for the help on this guys and the regex is working well

One other thought with this function im making

Func _NzbRename()
$aNzbList = _FileListToArray(@ScriptDir, "*.nzb", 1)
_ArrayDisplay( $aNzbList)
If $aNzbList = "" Then
MsgBox(64, "", " No Files To Change ", 3)
Exit
Else
Select
Case $aNzbList = 1 ;<<< Can this be accessed like this? Im basically saying does the array have only 1 entry
the regex etc after here

Basically if there is only one file in the array i want to do one thing but if there is 2 or more i will do another.

I also tried $i =1

This as i have it doesn't work

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