Home > Software engineering >  How to rename files based on CSV file with FOR /F loop?
How to rename files based on CSV file with FOR /F loop?

Time:05-23

I'm trying to automate renaming of files based on a CSV such as the one shown below:

Name,FullName

John,JohnDoe

Jane,JaneDoe

Joe,JoeDoe

Let's say I have 3 text files within the same folder of my .bat called John.txt, Jane.txt, Joe.txt and I want to rename John.txt to JohnDoe.txt, etc.

I am getting "The system cannot find the file specified" no matter how much I alter the filepath in my rename. Here is a basic rundown of what I have. What am I doing wrong here or what other way should I approach this? I appreciate all feedback.

@echo off
setlocal enabledelayedexpansion

set csvpath=C:\Users\user1\OneDrive\Documents\BatchExamples\stuff.csv

FOR /F "usebackq skip=1 tokens=1,2 delims=," %%g IN (!csvpath!) do (
    set person=%%g
    set name=%%h

    echo My name is !person! and my full name is !name!

    rename !person!.txt !name!.txt
)

pause

CodePudding user response:

This is how I would do it:

@echo off

set "csvpath=C:\Users\user1\OneDrive\Documents\BatchExamples\stuff.csv"

FOR /F "usebackq skip=1 tokens=1,2 delims=," %%g IN (`findstr /v /c:":-:-:" "%csvpath%"`) do (
    echo My name is "%%g" and my full name is "%%h"

    rename "%~dp0\%%g.txt" "%%h.txt"
)

pause

This code is a bit cleaner and more robust, in that file paths and names can have special characters (like &) without breaking the script.

findstr /v /c:"SEARCHSTRING" "FILEPATH" tells findstr to print every line within FILEPATH excluding (/v) lines with SEARCHSTRING. This doesn't really change much from what you had previously, however it is a bit more robust.

In the rename command, I set it to %~dp0 and then the file name, %~dp0 is the path to where your .bat script is.

  • Related