Reuben John Pengelly Reuben John Pengelly - 6 months ago 20
Linux Question

Linux rename files based on input file

I need to rename hundreds of files in Linux to change the unique identifier of each from the command line. For sake of examples, I have a file containing:

old_name1 new_name1
old_name2 new_name2


and need to change the names from new to old IDs. The file names contain the IDs, but have extra characters as well. My plan is therefore to end up with:

abcd_old_name1_1234.txt ==> abcd_new_name1_1234.txt
abcd_old_name2_1234.txt ==> abcd_new_name2_1234.txt


Use of
rename
is obviously fairly helpful here, but I am struggling to work out how to iterate through the file of the desired name changes and pass this as input into
rename
?

Edit: To clarify, I am looking to make hundreds of different rename commands, the different changes that need to be made are listed in a text file.

Apologies if this is already answered, I've has a good hunt, but can't find a similar case.

Answer
while read -r old_name new_name; do
    rename "s/$old_name/$new_name/" *$old_name*.txt
done < file_with_names

In this way, you read the IDs from file_with_names and rename the files replacing $old_name with $new_name leaving the rest of the filename untouched.