【问题标题】:Using a batch file to extract the variable part of a string to use in renaming txt files使用批处理文件提取字符串的可变部分以用于重命名 txt 文件
【发布时间】:2010-10-11 12:58:46
【问题描述】:

我正在使用批处理文件来处理具有以下形式的文本文件:CLL*1.txt、CLLM*2.txt,位于特定的“下载”文件夹中。所有文件都包含以下形式的字符串: “文件参考:0xxxx”,其中 xxxx 是唯一的数字标识符。

我正在尝试使用以下脚本将文件重命名为 CLL*xxxx.txt(其中 xxxx 替换整数后缀),但没有取得多大成功。谁能帮忙?:

set target="S:\download\"

SetLocal EnableDelayedExpansion enableextensions 

for /f "usebackq tokens=2 delims=:" %%i IN (`findstr /b "File Reference  :" %target%CLL*.txt`) do ( 

   ren %target%CLL*.txt CLL*%%i.txt

)


Endlocal

【问题讨论】:

    标签: string variables batch-file extract batch-rename


    【解决方案1】:

    findstr 不会向您返回任何单个值。它只会搜索一个字符串并返回整行。试试这个 vbscript

    Set objFS = CreateObject( "Scripting.FileSystemObject" )
    Set d = CreateObject("Scripting.Dictionary")
    strFolder= WScript.Arguments(0)
    Set objFolder = objFS.GetFolder(strFolder)
    For Each strFile In objFolder.Files
        If objFS.GetExtensionName(strFile) = "txt" Then    
            strFileName = strFile.Name          
            Set objFile = objFS.OpenTextFile(strFile)       
            Do Until objFile.AtEndOfStream 
                strLine=objFile.ReadLine
                If InStr(strLine,"File Reference") > 0 Then
                    s=Split(strLine,"File Reference : ")
                    num=Split( s(UBound(s))," ")
                    number=Mid(num(0),2) 'get the number
                    strNewFileName = "CLL"&CStr(number)&".txt"
                    objFile.Close               
                    strFile.Name = strNewFileName
                    Exit Do
                End If          
            Loop     
            Set objFile=Nothing
        End If  
    Next 
    

    另存为myscript.vbs并运行它

    C:\download_folder> cscript //nologo myscript.vbs c:\download_folder
    

    【讨论】:

    • 谢谢。使用 vbscript 格式化 txt 文件,但使用批处理文件最初重命名并根据内容移动它们。相信使用标记和分隔符只会传递 findstr /b 传递的字符串的一部分
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 2014-02-13
    • 2019-05-25
    • 2021-03-29
    • 2020-06-13
    相关资源
    最近更新 更多