-   Programming (
-   -   how to rename files recursively, only keeping last x digits plus extension (

furryspider 11-29-2009 11:24 AM

how to rename files recursively, only keeping last x digits plus extension
Hello everybody,

sorry if this has been answered (directly or indirectly) before, but I'm not really a programmer and after reading a lot of threads and man pages today with still no luck, I guess it's time to ask.

My problem is this:
I have a number of directories, all containing files of different name lenghts, including letters, numbers and possibly spaces. I want to recursively rename all of these files, so that only the _last_ 5 digits (not counting the extension) remain. In other words: I want to cut off all but the last 5 digits and not touch the extension.

I've tried to read up on tr, rename (perl version), sed, cut etc. and browsed through some threads here, but so far couldn't quite figure out how to do it.

If someone could point me to the right (standard) CLI tools and syntax, I'd heavily appreciate it! Thank you!

catkin 11-29-2009 11:46 AM

Not tested so only to illustrate the method


set -xv  # Comment out after debugging
set -o nounset

find . -type f -print0 | while IFS= read -r -d '' filepath
    case "$fn_noext" in
        *[0-9][0-9][0-9][0-9][0-9] )
            if [[ ! -e "$filepath_new" ]]; then
                echo mv "$filepath" "$filepath_new"  # Remove echo after testing
                echo "New filepath '$filepath_new' already exists. '$filepath' not renamed" >&2
        * )
            echo "'$filepath' does not end in 5 digits before extension; not renamed" >&2

furryspider 11-29-2009 01:55 PM

That is quite an impressive illustration, sir! It works like a charm! :)
Thanks a lot!

I'll have to do some reading before I fully understand your script. Seems it's mainly using pure bash functionality to 'parse' the filenames and put the desired parts back together. I don't think I would have found this solution by myself, so again, thanks for your help!

All times are GMT -5. The time now is 12:54 PM.