deko
deko

Reputation: 2636

Windows batch file: converting all files in subfolders

I need to write a batch file to convert every file in every subfolder. I came up to the following solution:

set INDIR=<some path>  
set OUTDIR=<some path>

mkdir "%OUTDIR%" 
for /f "tokens=1*delims=." %%f in ('dir %INDIR% /b /a-d') do (
    rem %%f is file name
    rem %%g is extension
    call convert_one . %%f %%g
  )
)  

for /f "delims==" %%d in ('dir %INDIR% /ad /b') do ( 
  rem %%d is relative path
  mkdir %OUTDIR%\%%d
  for /f "tokens=1*delims=." %%f in ('dir %INDIR%\%%d /b /a-d') do (
    rem %%f is file name
    rem %%g is extension
    call convert_one %%d %%f %%g
  )
)  

The problem is that it iterates through the first level subfolders only. When I add /s key to the dir command it returns full pathes instead of relative.
How can I improve the script to process all levels subfolders?
PS: I need separate values for relative path, file name and extension.

Upvotes: 0

Views: 641

Answers (2)

MC ND
MC ND

Reputation: 70941

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "INDIR=%cd%"
    set "OUTDIR=..\out"

    subst :: /d >nul 2>&1 & subst :: "%INDIR%"
    for /r "::\." %%a in  (*) do (
        if not exist "%OUTDIR%%%~pa" md "%OUTDIR%%%~pa"
        call convert_one  ".%%~pa" "%%~na" "%%~xa"
    )
    subst :: /d

This operates creating a subst drive, so the root of the drive point to the in folder. Then iterates over the folder structure recreating the structure in the output folder and calling the subroutine with the indicated parameters

Upvotes: 1

Magoo
Magoo

Reputation: 80203

You don't show us convert_one - but here's a few clues...

for /f "delims=" %%f in ('dir %INDIR% /b /s /a-d') do (
    rem %%~dpnf is file name and path
    rem %%~dpf is file absolute path
    rem %%~nf is file name-part
    rem %%~xf is extension
    call convert_one "%%~dpf" "%%nf" %%~xf
  )
)  

See for /?|more from the prompt for more...

(within your subroutine, %~n for n=1..9 strips quotes if needed - applying quotes means that "strings containing spaces" are regarded as a single string. - maybe make your destination directory there...?)

Upvotes: 2

Related Questions