Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux rename files based on input file

Tags:

linux

bash

rename

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.

like image 225
Reuben John Pengelly Avatar asked Dec 01 '14 15:12

Reuben John Pengelly


1 Answers

rename 's/^(abcd_)old_name(\d+_1234\.txt)$/$1new_name$2/' *.txt

Should work, depending on whether you have that package installed. Also have a look at qmv (rename-utils)

If you want more options, use e.g.

shopt -s globstart
rename 's/^(abcd_)old_name(\d+_1234\.txt)$/$1new_name$2/' folder/**/*.txt

(finds all txt files in subdirectories of folder), or

find folder -type f -iname '*.txt' -exec rename 's/^(abcd_)old_name(\d+_1234\.txt)$/$1new_name$2/' {} \+

To do then same using GNU find

like image 130
sehe Avatar answered Oct 23 '22 15:10

sehe