Batch file to rename physical files from CSV entries

This batch file will read a CSV file with “id” in “A” column, user name in “B” column and file name in “C” column. The problem statement is to read user name in column B in the CSV file and rename the file specified in column C with the user name.
Some tips:
a. The following line reads the CSV file in a loop with delimiter as comma:
FOR /F “skip=1 tokens=2-4 delims=,” %%a IN (%1) do ^

b. %%~xi automatically picks up the file extension from a file name.

c. ext is used as a variable here.
setlocal ENABLEDELAYEDEXPANSION enables proper usage of this variable.

d. %%a, %%b, %%c specifies columns A, B, C in the CSV file.

e. Following line extracts the file name extension and echoes it:
for %%i in (%%c) do echo %%~xi

f. The following line copies file name in C column with name in B column with extension variable “ext”
echo copying %%c “%%b!ext!”
Hence original file extensions are preserved while copying/ renaming.

g. The renamed files are copied to folder called “renamed” in the parent folder.

h. usage is rename_files.bat (csv-file)

i. Place the CSV file, bat file and photos in same parent folder

j. The if/else part appears because when an extra column appears in a column b data is pushed to c
column (four digit number in column A causes an extra column to appear in id column)

k. %1 represents the run time argument passed to the batch file.

@echo off
if not exist (%1) (
 echo Input file missing.  Usage: rename_jpg.bat (csv-file)
)
setlocal ENABLEDELAYEDEXPANSION
FOR /F "skip=1 tokens=2-4 delims=," %%a IN (%1) do ^
if [%%c]==[] (
for %%i in (%%b) do echo %%~xi
for %%i in (%%b) do (
 set "ext=%%~xi"
 )
 echo copying %%b "%%a!ext!"
 copy %%b "%%a!ext!"
 move "%%a!ext!" renamed
) else (
for %%i in (%%c) do echo %%~xi
for %%i in (%%c) do (
 set "ext=%%~xi"
 )
 echo copying %%c "%%b!ext!"
 copy %%c "%%b!ext!"
 move "%%b!ext!" renamed
)

example of CSV entries:

Id	User Name	File Name	
1	1408946308922	a2298d70-91a2-4254-a3bf-f721ee2d.jpg	
2	1408946892590	5bc14e6f-5922-4864-b5c6-ceb69ad0.jpg	
3	1408947330112	06545cfb-703a-4d57-aaa8-419b0295.jpg	
4	1408946289199	46f98f8d-b11a-4617-b05a-80c0ff53.jpg	

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Comments are closed.

%d bloggers like this: