Wednesday, December 15, 2010

Recursively rename files

I know, I know that's a very easy one... but just when I should have known how to do that in a shot, I didn't. And of course there are a lot of references for such things out there, so I'm absolutely not claiming to be original, but sorry if I don't post any references.
So, here is the thing: imaging you want to rename all files in a certain directory that are *.txt with *.back for example, including any subdirectories:

find . -type f -name "*.txt" -print| rename -n 's/(.*)txt$/$1back/g'

Remarks:
- this works only on linux (or where you have the command 'rename')
- rename accepts the perl regexp syntax, hence all this $1 for the substitution of the previous match (.*)
- tip: it's good to try using rename with -n option, which actually does nothing but showing what it would do without the -n option
- careful: if you fear that something nasty could happen with very depth directories and the find consuming lots of CPU or for whatever reason, you can include a -maxdepth 10 (or any other reasonable number), like this:

find . -maxdepth 10  -type f -name "*.txt" -print| rename -n 's/(.*)txt$/$1back/g'


- another thing that confused me as I tried it out: don't include the 'usual' *.[file_type] (in my case *.txt) at the end, after the rename 's/.../.../' part; it will prevent find from really diving into the subdirectories

No comments: