Search code examples
for-loopbatch-filebatch-rename

Rename all files in directory based on text they contain


I'm trying to loop through all .lss files in a folder, and grab a string that exists between two tags, save that value and rename the file using that string.

Example:

42982934829.lss -> contains string:

<surveyls_title><![CDATA[J.3200-1118 - Project Title]]></surveyls_title>

Rename to `J.3200-1118 - Project Title.lss`

Here is what I have so far, but I fear my syntax is badly incorrect..

@Echo off
Set Folder=X:\RenameTest
Set Files=*.lss
PushD %Folder%

For %%A in (%Files%) Do For /f %%B IN (
  'findstr "<surveyls_title>.*</surveyls_title>" "%ProjectTitle%"'
    ) Do Call :Rename ..
PopD
Goto :Eof

:Rename
Echo Ren %1 "%ProjectTitle%"

Solution

  • I suppose this is what you want.

    @echo off
    pushd "X:\RenameTest"
    for %%a in (*.lss) do for /f "tokens=3*delims=[]" %%i in ('type "%%a" ^| find "</surveyls_title>"') do echo ren "%%~a" "%%~i%%~xa"
    popd
    

    Just remove echo from the line once you are happy with the printed results.