Thursday, May 16, 2024
7
rated 0 times [  7] [ 0]  / answers: 1 / hits: 2583  / 1 Year ago, mon, february 27, 2023, 4:05:31

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?


More From » command-line

 Answers
7

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.


[#22069] Tuesday, February 28, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
laiuct

Total Points: 44
Total Questions: 105
Total Answers: 107

Location: Seychelles
Member since Mon, Feb 15, 2021
3 Years ago
laiuct questions
;