Using text list to batch-rename files
Suppose I have a folder with some 20 files (say, photos I took on a trip), and I want to rename them in one go, only there isn't any specific Perl expression I want to use (for example, if I'd like to add additional text to each name that's not part of the individual files' meta-data, such as descriptions and/or comments).
And suppose I can more easily generate a text file with what I want each file's name to be (or, if preferable, a 'before-and-after' sort of list).
Is there any way to apply the changes implied in that text list to the folder in question?
This looks like a job for xargs
.
If your file is formatted like this:
old_file1 new_file1
old_file2 new_file2
then you can do xargs -a your_file -n 2 mv
.
1. Open the terminal and change directory to the working directory (where the files to be renamed are located).
2. File names with numbers can alter the sequence therefor zero pad the numbers in file names by running the following code after changing .ext to your extension e.g. .txt .pdf etc.
rename 's/\d+/sprintf("%04d",$&)/e' *.ext
3. Put the list file, with the new names in sequential order, with extension, as file.list in the home folder. eg.
newname file x.jpg
newname file y.jpg
newname file z.jpg
4. Run the code below in terminal after changing .ext in the code to your extension e.g. .txt .pdf etc.
rm ~/undo.sh; for old in *.ext; do read new; mv -v "${old}" "${new}"; echo "mv" '"'$new'"' '"'$old'"' >> ~/undo.sh; chmod +x ~/undo.sh; done < ~/file.list
5. An undo.sh file will be created in home folder to undo the renames if needed.
6. If you don't need the undo file the following code is enough.
for old in *.ext; do read new; mv -v "${old}" "${new}"; done < ~/file.list