Ubuntu – Batch rename using a .csv

batch-renamecommand linecsv

I have 700 directories at one location and I need to rename them using a .csv file as shown below:

I want to replace names of Column_A with the entries of Column_B.

Column_A           Column_B

 F001               IC500
 F003               IC501
 F006               IC502
 F008               IC503
 ...                ...

How do I batch rename the directories?

Best Answer

First export your data as .csv file format like below:

F001,IC500
F003,IC501
F006,IC502
F008,IC503

Then run the below script to rename those directories to their new names:

while IFS=, read -a dirName; do
    echo mv -v "/singleFolder/${dirName[0]}" "/singleFolder/${dirName[1]}";
done < /path/to/file.csv

mv -v /singleFolder/F001 /singleFolder/IC500
mv -v /singleFolder/F003 /singleFolder/IC501
mv -v /singleFolder/F006 /singleFolder/IC502
mv -v /singleFolder/F008 /singleFolder/IC503
  • read -a used for splitting each line read into array based from IFS which I redefined that to comma,.

  • Each line reads into dirName variable.

  • With ${dirName[0]} we are getting the first part of the line(column A).
  • With ${dirName[1]} we are getting the last part of the line(column B).

  • mv command used for rename there.
    So with mv -v "/singleFolder/${dirName[0]}" "/singleFolder/${dirName[1]}", we are renaming the name of directories from columnA to new-name in columnB which are located in singleFolder directory.

  • -v option shows what is being done during running the command.


Also you can use the command without making the content of line as an array like this:

while IFS=, read -r oldName newName;do
    echo mv -v "/singleFolder/${oldName}" "/singleFolder/${newName}";
done < /path/to/file.csv

Note: remove echo command to performing rename on your real directories.