Ubuntu – How to batch rename files (images) based on CSV file

batch-renamecsvscripts

What I have and want to achieve:

  1. There are thousands of images in one folder.

  2. I have a CSV file with following columns:

    A: original name
    B: renamed name

    A typical row looks like this:

    "original-1.jpg","renamed-1.jpg"  
    "original-2.jpg","renamed-2.jpg"
    

    I can remove the quotes, that's not a problem.

  3. Now I want to use an app or run a script that will search for all of the images in column A and rename them to names in column B (e. g. original-1.jpg -> renamed-1.jpg).

There are some answers around, e. g.:

http://ubuntuforums.org/showthread.php?t=1069652

http://systembash.com/content/one-line-batch-rename-files-using-csv-input-file-and-awk/

However, there's some scripting involved and I'm not sure if all of those scripts affect only the folder where you store the script or they can rename all of the files on the disk that satisfy certain conditions. Of course, latter needs to be avoided.

What I am looking for is a simple guide how to rename files and how to choose a folder with files.

Thank you in advance.

Best Answer

This should work for you:

sed 's/"//g' files.csv | while IFS=, read orig new; do mv "$orig" "$new"; done 

Explanation:

  • sed 's/"//g' files.csv : remove the quotes
  • IFS=, : split the input on ,
  • while read orig new; do ... done : This will read each input line, split it on the value of $IFS (here a comma) and save the 1st field as $orig and the rest as $new.
  • mv "$orig" "$new" : this will rename the files as requested.

If your file only contains file names (like orig.jpg) and no paths (not /home/take2/orig.jpg or similar), the command above will only affect files in your current directory. So, you need to open a terminal, cd to the target directory and run it there.

Test first:

To test this, you can do a dry run first by printing the commands that will be run without actually executing them:

sed 's/"//g' files.csv | while IFS=, read orig new; do echo mv "$orig" "$new"; done 
Related Question