简体   繁体   English

使用批处理文件提取字符串的可变部分以重命名txt文件

[英]Using a batch file to extract the variable part of a string to use in renaming txt files

I'm using batch files to process text files with names of the form: CLL*1.txt, CLLM*2.txt located in a specific "download" folder. 我正在使用批处理文件来处理名称为以下形式的文本文件:位于特定“下载”文件夹中的CLL * 1.txt,CLLM * 2.txt。 All files contain a string of the form: "File Reference : 0xxxx", where xxxx is a unique numerical identifier. 所有文件均包含以下格式的字符串:“文件参考:0xxxx”,其中xxxx是唯一的数字标识符。

I am trying, without much success, to use the following script to rename the file to CLL*xxxx.txt (where xxxx replaces the integer suffix). 我正在尝试使用以下脚本将文件重命名为CLL * xxxx.txt(其中xxxx替换整数后缀),但没有太大的成功。 Can anyone help?: 谁能帮忙?

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

findstr will not return any single values to you. findstr不会向您返回任何单个值。 It will only search for a string and return the whole line. 它只会搜索一个字符串并返回整行。 try this vbscript 试试这个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 

save as myscript.vbs and run it 另存为myscript.vbs并运行它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM