Remove Number and period in filename vbsript - vbscript

I have already found a script that will replace underscore (_) and other text that I write in script. I need to modify this script so that it will also remove all the numbers in the filename too. I tried [0-9] and /d but that didn't remove the numbers in the filename. Also I tried to remove a period in the file name, but that also removed the file extension. So it took away the .csv too. Can someone help?
'========================================================
' VBScript to replace underscore in file name with space
' for each files in a folder
' Written by ApOgEE of http://coderstalk.blogspot.com
'========================================================
Dim sName
Dim fso
Dim fol
' create the filesystem object
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
' get current folder
Set fol = fso.GetFolder(".")
' go thru each files in the folder
For Each fil In fol.Files
' check if the file name contains underscore
If InStr(1, fil.Name, "_") <> 0 Then
' replace underscore with space
sName = Replace(fil.Name, "_", " ")
' rename the file
fil.Name = sName
End If
Next
' echo the job is completed
WScript.Echo "Completed!"

The Replace function does only simple string replacements. It doesn't support wildcards or patterns. You're looking for regular expressions:
Set re = New RegExp
re.Pattern = "[0-9_.]"
re.Global = True
For Each fil In fol.Files
fil.Name = re.Replace(fil.Name, " ")
Next

Related

Renaming multiple files in a loop

I have a folder with 8 Excel files with the following naming convention:
date_All_Groups
date_HRFull_Status_All
date_RME_Groups_Excluded
These files are used for monthly reports, therefore the date will obviously always be different.
I will be using a macro to manipulate the data in each worksheet, however I cannot create the macro due the changing file name (the date) - the only guarantee I have is that each of these files will DEFINITELY contain a partial string match.
I have a script that finds the files in the location and will rename the file, but it only renames 1 file and its not the first file in the folder.
My issue is using the For Each loop effectively.
Here's the code I have:
Dim fso, folder, file
Dim folderName, searchFileName, renameFile1, renameFile2, renameFile3, renameFile4, renameFile5, renameFile6, renameFile7, renameFile8
'Path
folderName = "C:\test\"
'Future FileName
renameFile1 = "All Groups.csv"
renameFile2 = "Groups Excluded.csv"
renameFile3 = "No Exclusions.csv"
renameFile4 = "HR.csv"
renameFile5 = "AD Users.csv"
renameFile6 = "Encryption Status.csv"
renameFile7 = "ePO4 Not Encrypted.csv"
renameFile8 = "ePO5 Not Encrypted.csv"
' Create filesystem object and the folder object
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderName)
' Loop over all files in the folder until the searchFileName is found
For Each file In folder.Files
' See If the file starts with the name we search
If InStr(file.Name, "All_Groups") then
file.Name = renameFile1
End If
If InStr(file.Name, "Groups_Excluded") Then
file.Name = renameFile2
End If
If InStr(file.Name, "No_Exclusions") Then
file.Name = renameFile3
End If
If InStr(file.Name, "HR") Then
file.Name = renameFile4
End If
If InStr(file.Name, "AD_Users") then
file.Name = renameFile5
End If
If InStr(file.Name, "Encryption_Status") then
file.Name = renameFile6
End If
If InStr(file.Name, "ePO4") then
file.Name = renameFile7
End If
If InStr(file.Name, "ePO5") then
file.Name = renameFile8
End If
Exit For
' echo the job is completed
WScript.Echo "Completed!"
Next
The original code I found was exactly as above, but with only one If statement inside the For Each loop and the Exit For was inside the If statement.
Currently when I execute the script, the code renames only one file and its always the HR file first.
If I execute the script again, it then starts with All Groups, then Groups Excluded, and so on.
And the "Echo Completed" does not do anything either.
If you just want to rename your files to "canonical" names you could do something like this, assuming that you just want the date from the beginning of the filename removed and the underscores replaced with spaces:
Set re = New RegExp
re.Pattern = "\d{4}-\d{2}-\d{2}_(.*\.csv)"
For Each f In folder.Files
For Each m In re.Execute(f.Name)
f.Name = Replace(m.Submatches(0), "_", " ")
Next
Next
If the files have the same "date" you only need Find for that, for excample (if the date is a iso date "YYYYMMDD") (Date Returns "today" date)
IsoDate=CStr(Year(Date)) & Right("0" & CStr(Month(Date)),2) & Right("0" & CStr(Day(Date)),2)
And the for each:
For Each file In folder.Files
If InStr(file.Name, IsoDate) = 1 then 'if is in the start of the string
file.Name = Mid(file.Name, Len(IsoDate)+1) 'The same name with out date
End IF
Next

Rename part of file

I require a VBScript that finds the most recent file in a folder and renames it. I have been able to write the script so that it finds the most recent file. However, I cannot figure out how to correctly have the file renamed once identified. I have been able to rename the file with a basic name, confirming the script works.
The file name needs the letter "A" added in the middle.
The file will already be saved as 20160229_TITLES and it needs to become 20160229A_TITLES.
Below is a script I tried to just pull the year and add the "A". I figured if I could get the year to add to the beginning, I could then add in the month and year. The date will always be the current date. This continues to cause an error message.
Option Explicit
Dim fso, folder, file, Date, recentFile
Dim folderName, searchFileName, renameFileTo
folderName = "C:\Ticket\Test\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderName)
Set recentFile = Nothing
For Each file In folder.Files
If (recentFile is Nothing) Then
Set recentFile = file
ElseIf FormatDateTime(file.DateLastModified) = Date Then
Set recentFile = file
End If
Next
recentFile.Name = Replace(recentFile.Name, "_", "A_")
Assuming that the filename will always consist of a date followed by an underscore and some other text you could do several things:
replace underscores with "A_" (if there is only one underscore in the name):
file.Name = Replace(file.Name, "_", "A_")
split the name at the first underscore, append "A" to the first fragment and join the fragments back together:
arr = Split(file.Name, "_", 2)
arr(0) = arr(0) & "A"
file.Name = Join(arr, "_")
do a regular expression replacement:
Set re = New RegExp
re.Pattern = "^(\d{8})_"
file.Name = re.Replace(file.Name, "$1A_")
The answer #Ansgar provided helped me correctly rename the file, however, I learned that the script only searched for any file that was newer than any other file and renamed it. The following script correctly renames the file that was modified today. Thank you for all your help #Ansgar. :)
Option Explicit
Dim fso, folder, file, todaysDate, recentFile
Dim folderName, searchFileName, renameFileTo
folderName = "C:\Ticket\Test\"
todaysDate = Date()
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderName)
set recentFile = Nothing
For each file In folder.Files
If (recentFile is Nothing) Then
Set recentFile = file
ElseIf DateValue (file.DateLastModified) = todaysDate then
Set recentFile = file
Exit For
End IF
Next
recentFile.Name = Replace(recentFile.Name, "_", "A_")

Search Keyword and rename entire file using VBS

I spent a quite a bit looking around. I did find one method that was extremely close to what I was looking for but it replaces keywords.
Dim sName
Dim fso
Dim fol
' create the filesystem object
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
' get current folder
Set fol = fso.GetFolder("F:\Downloads")
' go thru each files in the folder
For Each fil In fol.Files
' check if the file name contains underscore
If InStr(1, fil.Name, "[wizardry] tv show bob - 13") <> 0 Then
' replace underscore with space
sName = Replace(fil.Name, "[wizardry] tv show bob - 13", "tv show bob S03E13")
' rename the file
fil.Name = sName
End If
Next
' echo the job is completed
WScript.Echo "Completed!"
But as I said, the only issue is that it repalces the keywords. I want it to replace the ENTIRE file name with what I want.
Most of the files will have a group tag before hand like this: [wizardy] tv show bob - 13
I want to make sure the group tag is gone so I can actually copy the file over. Unless there is a way to pull the file name of the current file I renamed.
Any help is appreciated, thanks.
Instead of replace, you need to generate a new name with the original extension, I think? If not, please give us more detail.
Dim sName
Dim fso
Dim fol
Dim fil
Dim ext
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set fol = fso.GetFolder("F:\Downloads")
For Each fil In fol.Files
'may need to specify a comparison
If InStr(1, fil.Name, "[wizardry] tv show bob - 13", vbTextCompare) <> 0 Then
ext = fso.GetExtensionName(fil)
If Len(ext) > 0 Then ext = "." & ext
sName = "tv show bob S03E13" & ext
fil.Name = sName
End If
Next
WScript.Echo "Completed!"

Script help needed editing ini file

I'm trying to edit one line in an ini file. DeviceName=APPLE to DeviceName="The User Input". I have it almost there from bits and pieces across the internet. It works except the end result is my file jwalk.ini with the correct entry after user input but the ini file has been renamed to just .ini, no jwalk before ini. I must be missing something. The file jwalk.ini already will exist I just need to edit it with the new user input and leave the file named the same.
My Script:
Const ForReading = 1
Const ForWriting = 2
Const OpenAsASCII = 0
Const CreateIfNotExist = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open existing file for read access.
strInput = "c:\MyFolder\jwalk.ini"
Set objInput = objFSO.OpenTextFile(strInput, ForReading)
' Prompt for device name.
strDeviceName = InputBox("Enter devicename", "JWalk PC Name or Session Name")
' Specify the new file name.
strOutput = "c:\MyFolder\" & strComputer & ".ini"
' Create new file with write access.
Set objOutput = objFSO.OpenTextFile(strOutput, _
ForWriting, CreateIfNotExist, OpenAsASCII)
' Process input file.
Do Until objInput.AtEndOfStream
' Read next line of the input file.
strLine = objInput.ReadLine
' Search for line to be modified.
' Make search case insensitive.
If (InStr(LCase(strLine), "devicename=") > 0) Then
' Replace the line.
' You could also modify the line.
strLine = "devicename=" & strDeviceName
End If
' Write line to the output file.
objOutput.WriteLine strLine
Loop
' Clean up.
objInput.Close
objOutput.Close
' Delete the original file.
objFSO.DeleteFile(strInput)
Any ideas? Thanks.
If you'd have used Option Explicit, you'd have been told that
strOutput = "c:\MyFolder\" & strComputer & ".ini"
uses the undefined/uninitialized variable strComputer.
Here you are passing "strComputer" as a var, but never set it's value:
' Specify the new file name.
strOutput = "c:\MyFolder\" & strComputer & ".ini"
If you are trying to get the computer name you could consider this:
' Specify the new file name.
strOutput = "c:\MyFolder\" & GetComputerName() & ".ini"
Function GetComputerName()
Dim ob
Set ob = Wscript.CreateObject("Wscript.Network")
GetComputerName = ob.ComputerName
Set ob = nothing
End Function

Insert "-" at a specific position using VBScript

I have a file which has multiple lines.
It is required to have "-" after 8th position in every line.
I can read lines with "-" at 9th position, but I am not able to write "-" at the 9th position if it is not there.
Any help would be really appreciated.
You can't insert characters in a VBScript string, because these are immutable; you'll have to concatenate a new string from Left(sOrgStr, 8) & "-" & Mid( sOrgStr, 9). (The numbers are +-1 depending on how you count.)
This vbs will
open a file C:\temp\log.txt,
make a global change with a single regexo
write the new updated text back over the original file
Please change the path to your file to suit in this line
StrFileName = "C:\temp\log.txt"
Const ForReading = 1
Const ForWriting = 2
Dim objFSO
Dim objTF
Dim objRexex
Dim StrFileName
Dim strTxt
StrFileName = "C:\temp\log.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(StrFileName, ForReading)
Set objregex = CreateObject("vbscript.regexp")
strTxt = objTF.ReadAll
objTF.Close
With objregex
.Global = True
.MultiLine = True
.Pattern = "^(.{8})[^-](.*)$"
strTxt = .Replace(strTxt, "$1" & "-" & "$2")
End With
Set objTF = objFSO.OpenTextFile(StrFileName, ForWriting)
objTF.Write strTxt
objTF.Close
you can fix the strings you read using this code:
s="input string"
if (mid(s,9,1)<>"-") then 'the 9th character isn't "-"
s=left(s,8) & "-" & mid(s,9)
end if
I suggest you'll open your file for input and re-write it into another text file.
You could use regular expressions.
If you're reading the lines 1-by-1 I think you need something like
Set objRe = New RegExp
' this will match any line having 9 or more characters,
' where the 9-th character is not "-", and capture the first 8 characters in the group #1
objRe.Pattern = "^(.{8})[^-]"
' Open the file, read lines, in the inner loop, call:
line = objRe.Replace( line, "$1-" ) ' This will replace the RE with the group #1 followed by '-'

Resources