sn1ks
sn1ks

Reputation: 103

Loop through folder with files including a space

I want to loop through a folder and let run an algorithm on each .tif file found. Unfortunately this does not work for files which have a space character in their name. As my path already contains folders with space, i put the variable which stores the path name in double-quotation marks.

FOR /F %%k IN ('DIR /B "%mypath_import%"*.tif') DO (

SET infile=%%k
SET outfile=!infile:.tif=_UTM.tif!
REM ... do something 

This is my attempt so far but it won't work for the files which include a space as well.

Upvotes: 0

Views: 305

Answers (1)

user7818749
user7818749

Reputation:

You done need all that. You can use the normal for loop without having to use /f

@echo off
setlocal enabledelayedexpansion
set "mypath_import=C:\Some path"
for %%i in ("%mypath_import%*.tif") do (
   set "infile=%%~i"
   echo "!infile:.tif=UTM.tif!"
)

The above will however echo full path to and file name, if you want filename only with extension:

@echo off
setlocal enabledelayedexpansion
set "mypath_import=C:\Some path"
for %%i in ("%mypath_import%*.tif") do (
   set "infile=%%~nxi"
   echo "!infile:.tif=UTM.tif!"
)

or without the need to delayedexpansion

@echo off
set "mypath_import=C:\Some path"
for %%i in ("%mypath_import%*.tif") do echo %%~dpni_UTM%%~xi

and again if you require the name and extension only.

@echo off
set "mypath_import=C:\Some path"
for %%i in ("%mypath_import%*.tif") do echo %%~ni_UTM%%~xi

EDIT

As per comment from @Stephan, keep in mind if you are doing actual renames and you run the script more than once it will keep on appending _UTM each time. So you'll get filename_UTM_UTM.tif etc. So you can exclude files from the loop by including findstr

for /f "delims=" %%i in ('dir /b *.tif ^|findstr /eiv "_UTM.tif"') do echo %%~ni_UTM%%~xi

Upvotes: 2

Related Questions