Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename files in bash to increase number in name?

Tags:

linux

bash

rename

I have a few thousand files named as follows:

Cyprinus_carpio_600_nanopore_trim_reads.fasta                
Cyprinus_carpio_700_nanopore_trim_reads.fasta               
Cyprinus_carpio_800_nanopore_trim_reads.fasta                
Cyprinus_carpio_900_nanopore_trim_reads.fasta 
Vibrio_cholerae_3900_nanopore_trim_reads.fasta

for 80 variations of the first two words (80 different species), i would like to rename all of these files such that the number is increased by 100 - for example:

Vibrio_cholerae_3900_nanopore_trim_reads.fasta 

would become

Vibrio_cholerae_4000_nanopore_trim_reads.fasta

or

Cyprinus_carpio_300_nanopore_trim_reads.fasta

would become

Cyprinus_carpio_400_nanopore_trim_reads.fasta

Unfortunately I can't work out how to get to rename them, i've had some luck with following the solutions on https://unix.stackexchange.com/questions/40523/rename-files-by-incrementing-a-number-within-the-filename

But i can't get it to work for the inside of the name, i'm running on Ubuntu 18.04 if that helps

like image 740
MolEcologist29 Avatar asked Dec 24 '22 03:12

MolEcologist29


1 Answers

If you can get hold of the Perl-flavoured version of rename, that is simple like this:

rename -n 's/(\d+)/$1 + 100/e' *fasta

Sample Output

'Ciprianus_maximus_11_fred.fasta' would be renamed to 'Ciprianus_maximus_111_fred.fasta'
'Ciprianus_maximus_300_fred.fasta' would be renamed to 'Ciprianus_maximus_400_fred.fasta'
'Ciprianus_maximus_3900_fred.fasta' would be renamed to 'Ciprianus_maximus_4000_fred.fasta'

If you can't read Perl, that says... "Do a single substitution as follows. Wherever you see a bunch of digits next to each other in a row (\d+), remember them (because I put that in parentheses), and then replace them with the evaluated expression of that bunch of digits ($1) plus 100.".

Remove the -n if the dry-run looks correct. The only "tricky part" is the use of e at the end of the substitution which means evaluate the expression in the substitution - or I call it a "calculated replacement".

like image 184
Mark Setchell Avatar answered Dec 30 '22 09:12

Mark Setchell