Search code examples
bashfind

Recursively rename files based on the upper folder names


There is a folder structure like this

./A/B/C/D/file.txt

and I want to start from . and recursively find file.txt and rename it to the two upper level folder names. So the example above should be ./A/B/C/D/C.D.txt.

I can use find to recursively rename the files, but I don't know how combine that with basename and dirname to extract C and D upon a match. How can I do that?


Solution

  • Using bash arrays:

    find . -name 'file.txt' -exec bash -c '
        IFS=/
        for p; do
            a=($p)
            n=${#a[@]}
            ((n>3)) && echo mv "$p" "${a[*]:0:n-1}/${a[n-3]}.${a[n-2]}.txt"
        done
    ' -- {} +