我有一个基本的vbs代码,用于在第一个下划线分割文件名。例如:t_e_s_t变为t。 我不想拆分文件名,我想删除文件名的注释 这将由“。”组成。 “_”和空格。
有人可以看看代码并告诉我如何修改它吗?
Option Explicit
Dim strPath
Dim FSO
Dim FLD
Dim fil
Dim strOldName
Dim strNewName
Dim strFileParts
'Define the path to the file
strPath = inputbox("File path:")
'Create the instance of the FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
'Set the folder you want to search. NOTE - some antivirus may not like this
Set FLD = FSO.GetFolder(strPath)
'Loop through each file in the folder
For Each fil in FLD.Files
'Get complete file name with path
strOldName = fil.Path
'Check the file has an underscore in the name
If InStr(strOldName, "_") > 0 Then
'Split the file on the underscore so we can get everything before it
strFileParts = Split(strOldName, "_")
'Build the new file name with everything before the
'first under score plus the extension
strNewName = strFileParts(0) & ".txt"
'Use the MoveFile method to rename the file
FSO.MoveFile strOldName, strNewName
End If
Next
'Cleanup the objects
Set FLD = Nothing
Set FSO = Nothing
答案 0 :(得分:0)
怎么样:
strNewName = Replace(strOldName, "_", "") & ".txt"
答案 1 :(得分:0)
您应该准确指定应将哪些输入转换为输出,而不是发布不能执行所需操作的代码。例如:“t e.s_t”应该成为“测试”。然后很容易想出一些概念证明代码:
>> Function qq(s) : qq = """" & s & """" : End Function
>> Function clean(s)
>> clean = Replace(Replace(Replace(s, " ", ""), ".", ""), "_", "")
>> End Function
>> a = Array("test", "t e s t", "t_e.s t")
>> For i = 1 To UBound(a)
>> c = clean(a(i))
>> WScript.Echo qq(a(i)), qq(c), CStr(c = a(0))
>> Next
>>
"t e s t" "test" True
"t_e.s t" "test" True
>>
以及非常有趣的问题:
答案 2 :(得分:0)
使用正则表达式:
Set re = New RegExp
re.Pattern = "[._ ]"
re.Global = True
For Each fil in FLD.Files
basename = FLD.GetBaseName(fil)
extension = FLD.GetExtensionName(fil)
fil.Name = re.Replace(basename, "") & "." & extension
Next
如果你想破坏扩展名并为每个文件追加一个新的扩展名.txt
,而不管其类型如何使用此循环:
For Each fil in FLD.Files
fil.Name = re.Replace(fil.Name, "") & ".txt"
Next