0

我有一个基本的 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
4

3 回答 3

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
于 2013-10-02T07:36:25.743 回答
0

怎么样:

strNewName = Replace(strOldName, "_", "") & ".txt"
于 2013-10-02T07:09:33.793 回答
0

您应该准确指定应该将什么输入转换为什么输出,而不是发布不符合您要求的代码。例如:“t e.s_t”应该变成“test”。然后很容易想出一些概念验证代码:

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

以及非常有趣的问题,例如:

  1. 为什么要将修改应用于完整路径(strOldName = fil.Path)?
  2. 扩展之前的点应该怎么做?
于 2013-10-02T07:11:30.943 回答