I am trying to write a vbscript to recursively rename any files in a folder.
My final plan will be to copy the folder to a zip file, but it fails if the files have any characters apart from
e.g (a-z) or (0-9) or "_", " ".
For example, if the file has characters other than English in the file name, it will not allow me to copy the file to the zip. I have looked at various websites and could have an answer in batch as well.
I am quite new to regex, having started learning about it yesterday.
The error I am getting is "File already Exists".
My script:
Const ForReading = 1
Const ForWriting = 2
Const ForAppend = 8
Const OverwriteExisting = TRUE
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = scriptdir & "\Fragments"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.Pattern = "[^A-Za-z_0-9-\n\r]"
For Each objFile in colFiles
If regEx.test(objFile.Name) = true Then
FirstlevelNewFileName = objRegEx.Replace(objFile.Name, "_")
objFSO.MoveFile objFile, FirstlevelNewFileName
End If
Next
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
NewFileName = objRegEx.Replace(objFile.Name, "_")
objFSO.MoveFile objFile.Path, NewFileName
Next
ShowSubFolders Subfolder
Next
End Sub
Thank you for your time!
I think your code have got issues with the Movefile statements(when you are trying to rename files). You are providing only the file name as the Destination parameter. You should provide full path there. I have made changes as shown below.
NOTE: I did not change any of the Logic.
Const ForReading = 1
Const ForWriting = 2
Const ForAppend = 8
Const OverwriteExisting = TRUE
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = scriptdir & "\Fragments"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
Set objRegEx = new Regexp
objRegEx.Global = True
objRegEx.Pattern = "[^\w.]" 'looks for non-word characters and also not .(for the extension)
For Each objFile in colFiles
If objRegEx.test(objFile.Name) = true Then 'Changed this. You had only used the variable RegEx here instead of objRegEx
FirstlevelNewFileName = objRegEx.Replace(objFile.Name, "_")
objFile.Move objStartFolder&"\"&FirstlevelNewFileName 'Provided the full file path here. Used the File Object itself
EndIf
Next
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
NewFileName = objRegEx.Replace(objFile.Name, "_")
objFile.Move Subfolder.Path&"\"&NewFileName 'passed the full path here again
Next
ShowSubFolders Subfolder
Next
End Sub
Related
trying to replace in a folder different color values with a new one this is my starting code:
Option Explicit
Dim objFSO, strFolder, objFolder, objFile
Dim strOldValue, strNewValue, objRead, strContents, objWrite
Const ForReading = 1
Const ForWriting = 2
strFolder = "..\..\chrome\OPCEN\TABS"
strOldValue = "#******"
strNewValue = "#F5F5F5"
UPDATE: this is the working code using RegEx (but is pointing to the file not to the whole folder)
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("..\..\chrome\OPCEN\TABS\tabs.css", ForReading)
strText = objFile.ReadAll
objFile.Close
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.IgnoreCase = False
objRegEx.Pattern = "\#[A-Z 0-9]{6}"
strNewText = objRegEx.Replace(strText, "#F5F5F5")
Set objFile = objFSO.OpenTextFile("..\..\chrome\OPCEN\TABS\tabs.css", ForWriting)
objFile.WriteLine strNewText
objFile.Close
Use For Each loop to processing files and Regular Expressions to replace your strings.
Try my way :
Const ForReading = 1
Const ForWriting = 2
Set fso=Createobject("Scripting.FileSystemObject")
Set objRegEx = New RegExp
FolderName = "..\..\chrome\OPCEN\TABS"
Set objFolder = fso.GetFolder(FolderName)
Set objFileCol = objFolder.Files
For Each obFile In objFileCol
If Right(obFile,3)="css" Then 'Check all files extensions.
Set objFile = fso.OpenTextFile(obFile, ForReading)
strText = objFile.ReadAll
objFile.Close
objRegEx.Global = True
objRegEx.IgnoreCase = False
objRegEx.Pattern = "\#[A-Z 0-9]{6}"
strNewText = objRegEx.Replace(strText, "#F5F5F5")
Set WriteFile = fso.OpenTextFile(obFile, ForWriting)
WriteFile.WriteLine strNewText
WriteFile.Close
End if
Next
I'm currently having difficulty with a VBScript I'm writing that contains several read and replaces from a text file. The expression I'm using finds the expression and replaces it, but adds three tab spaces afterwords, making the original line below it mess up the formatting. Here's a picture of what I'm talking about:
Here's a pastebin of the before and after, rather than an image:
https://pastebin.com/Uw3H59QK
Here's my RegExp code:
Set fso = CreateObject("Scripting.FileSystemObject")
Dim strPath
strPath = SelectFolder( "" )
If strPath = vbNull Then
WScript.Echo "Script Cancelled - No files have been modified" 'if the user cancels the open folder dialog
Else
WScript.Echo "Selected Folder: """ & strPath & """" 'prompt that tells you the folder you selected
End If
Function SelectFolder( myStartFolder )
Dim objFolder, objItem, objShell
Dim objFolderItems
On Error Resume Next
SelectFolder = vbNull
Set objShell = CreateObject( "Shell.Application" )
Set objFolder = objShell.BrowseForFolder( 0, "Please select the .dat file location folder", 0, myStartFolder)
set objFolderItems = objFolder.Items
If IsObject( objFolder ) Then SelectFolder = objFolder.Self.Path
Set objFolder = Nothing
Set objShell = Nothing
On Error Goto 0
End Function
Set re = New RegExp 'Replacing Position Lines
re.Pattern = "Pos = \((.*)\)"
re.Global = True
re.IgnoreCase = True
For Each f in fso.GetFolder(strPath).Files
If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
text = f.OpenAsTextStream.ReadAll 'reading the text file
f.OpenAsTextStream(2).Write re.Replace(text, """Position"" : mathutils.Vector(($1)),")
count = count + 1
End If
Next
Set reAngles = New RegExp 'Replacing Angles
reAngles.Pattern = "Angles = \((.*)\)"
reAngles.Global = True
reAngles.IgnoreCase = True
For Each f in fso.GetFolder(strPath).files
If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
text = f.OpenAsTextStream.ReadAll
f.OpenAsTextStream(2).Write reAngles.Replace(text, """Angles"" : mathutils.Vector(($1)),")
End If
Next
Set reNames = New RegExp 'Replacing Names
reNames.Pattern = "Name = (.*)"
reNames.Global = True
'reNames.Multiline = True
reNames.IgnoreCase = True
For Each f in fso.GetFolder(strPath).files
If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
text = f.OpenAsTextStream.ReadAll
f.OpenAsTextStream(2).Write reNames.Replace(text, """Name"" : ""$1"",")
End If
Next
My best guess is that the wildcard is grabbing more info than needed...but I'm unsure how to fix that. I used a lot of these expressions in Notepad++ so I was hoping to translate them to a VBS easily!
I am looking to clean up a .csv file for a database import. I am using the following vbs function and would like to incorporate '' to vbNull. I find it hard to understand RegEx. Can this even be done?
Function removeEmbeddedCommasInCSVTextField (strtoclean)
Dim objRegExp, outputStr
Set objRegExp = New Regexp
objRegExp.IgnoreCase = True
objRegExp.Global = True
objRegExp.Pattern = """[^""]*,[^""]*"""
Set objMatch = objRegExp.Execute( strtoclean )
corrected_row = strtoclean
For Each myMatch in objMatch
matched_value = myMatch.Value ' retrieves text column with embedded commas
cleaned_value = replace(matched_value, ",","") ' removes embeddes commans from column
corrected_row = replace(corrected_row, matched_value, cleaned_value) 'take row and replaced bad value with good value (no commas)
Next
removeEmbeddedCommasInCSVTextField = corrected_row
End Function
MAIN:
Set MyFile = fso.CreateTextFile(strShareDirectory & "fixed.txt", True)
Set f = fso.OpenTextFile(strShareDirectory & filename)
Do Until f.AtEndOfStream
before_clean = f.ReadLine
after_clean = removeEmbeddedCommasInCSVTextField(before_clean)
MyFile.WriteLine(after_clean)
'WScript.Echo after_clean
Loop
f.Close
MyFile.Close
I have this VBS code:
Option Explicit
Dim reMethod, reInterface
Dim vaction
Dim fileService
Dim mService
Dim lineService
Dim objFSO
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set fileService = objFSO.OpenTextFile("GIISAssuredController.java" , ForReading)
Set reMethod = new regexp
reMethod.Pattern = """\w+?""\.equals\(ACTION\)[\s\S]*?\{[\s\S]*?\.([^(]*)\("
reMethod.IgnoreCase = True
reMethod.Global = True
Do Until fileService.AtEndOfStream
lineService = fileService.ReadLine
For Each mService In reMethod.Execute(lineService)
vaction = mService.Submatches(0)
Set reInterface = new regexp
Wscript.Echo vaction
Next
Loop
And 'GIISAssuredController.java':
} else if ("hello".equals(ACTION)) {
Integer assuredNo = giisAssuredService.saveAssured(assured);
The regex pattern is not working.
I am expecting the output to be is:
saveAssured
But instead, it's not echoing anything. I tried the regex pattern here > https://regex101.com/r/kH3aZ4/1, and it's getting the 'saveAssured' string.
This question is related to: Multiline REGEX using VB Script
If the expression needs to match a text that spawns over multiple lines, but you read the file line by line and test line by line, there will never be a match.
Option Explicit
Const ForReading = 1
Dim code
code = CreateObject("Scripting.FileSystemObject" _
).OpenTextFile("GIISAssuredController.java" , ForReading _
).ReadAll()
Dim mService
With new RegExp
.Pattern = """\w+?""\.equals\(ACTION\)[\s\S]*?\{[\s\S]*?\.([^(]*)\("
.IgnoreCase = True
.Global = True
For Each mService in .Execute(code)
WScript.Echo mService.Submatches(0)
Next
End With
I am attempting to use a vbs script to replace the limit value in a .ini file that contains the following line:
CC_refund_limit=####.##
Unfortunately the ####.## can be any dollar value. I am replacing with a standard:
CC_refund_limit=500.00
I have attempted the following with every variation of \d \d+ enclosed in every bracket known to mankind and have even attempted [0-999] on a test file. The only way I can get this to work has been with the following code and only if the string contains an actual dollar value as written. I have over 1600 instances on as many different servers to replace this on.
Any guidance would be appreciated:
`Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "CC_refund_limit=200.00", "CC_refund_limit=500.00")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForWriting)
objFile.WriteLine strNewText
objFile.Close
`
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForReading)
strText = objFile.ReadAll
objFile.Close
Set r = New Regexp
With r
.pattern = "CC_refund_limit=\d+\.\d+"
.global = true
End with
StrNewText = r.Replace(strText,"CC_refund_limit=500.00")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForWriting)
objFile.WriteLine strNewText
objFile.Close