LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   how to rename files recursively, only keeping last x digits plus extension (http://www.linuxquestions.org/questions/programming-9/how-to-rename-files-recursively-only-keeping-last-x-digits-plus-extension-772265/)

furryspider 11-29-2009 10: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 10:46 AM

Not tested so only to illustrate the method
Code:

#!/bin/bash

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

find . -type f -print0 | while IFS= read -r -d '' filepath
do
    path="${filepath%/*}"
    fn="${filepath##*/}"
    ext="${fn##*.}"
    fn_noext="${fn%.$ext}"
    case "$fn_noext" in
        *[0-9][0-9][0-9][0-9][0-9] )
            fn_noext_new="${fn_noext:((${#fn_noext}-5))}"
            filepath_new="$path/$fn_noext_new.$ext"
            if [[ ! -e "$filepath_new" ]]; then
                echo mv "$filepath" "$filepath_new"  # Remove echo after testing
            else
                echo "New filepath '$filepath_new' already exists. '$filepath' not renamed" >&2
            fi
            ;;
        * )
            echo "'$filepath' does not end in 5 digits before extension; not renamed" >&2
    esac   
done


furryspider 11-29-2009 12: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 05:28 AM.