Strip Filenames and Rename

command linerename

What rename command can I use which will delete the present filenames in a directory and replace them with alphanumeric filenames?

Such as gg0001, gg0002, et cetera? And I'd like the command to work on files with any type of extension. And I'd like the extension to be retained.

I'd prefer that the Perl rename be used.

I've tried this command, but it just prepends the "gg" to the filenames whereas I want the original filenames replaced:

rename 's/^/gg_/' *

Best Answer

You don't really need the rename command for this, you can do it directly in the shell:

c=0; for i in *; do let c++; mv "$i" "gg_$(printf "%03d" $c)${i#"${i%.*}"}"; done

The printf "%03d" $c will print the $c variable, padding it with 3 leading 0s as needed. The let c++ increments the counter ($c). The ${i#"${i%.*}"} extracts the extension. More on that here.

I would not use rename for this. I don't think it can do calculations. Valid Perl constructs like s/.*/$c++/e fail and I don't see any other way to have it do calculations. That means you would still need to run it in a loop and have something else increment the counter for you. Something like:

c=0;for i in *; do let c++; rename -n 's/.*\.(.*)/'$c'.$1/' "$i"; done

But there's no advantage over using the simpler mv approach.

Related Question