Search code examples
file-renamebatch-rename

Add prefix of root folder to all files in directory/subdirectories


So I have a bunch of directories that are kind of like this (but with more files):

1-0
    file1
    file2
    folder
        file 3
1-1
    file1
    file2
    folder
        file 3
etc.

And as the question asks I want to prefix the 1-0, 1-1 to all the "files" in the directories and subdirectories of the root folder being the 1-0 etc. Like follows:

1-0
    1-0file1
    1-0file2
    folder
        1-0file 3
1-1
    1-1file1
    1-1file2
    folder
        1-1file 3
etc.

I've tried a few cmd/batch solutions from other questions and ReNamer but I couldn't find anything that quite did what I wanted. Pretty inexperienced with this kind of stuff so I could have missed something for sure. ReNamer I can do it but I have to do each directory individually and I have a fair few that I am trying to rename so it's a bit impractical.


Solution

  • I would find this in general a quite terrible idea to do... I cannot imagine a situation where on the long term this may really has been a good idea. One of the reasons is that it just duplicates structural information of the location in the filename itself. Why ?...

    On a linux shell there are certainly various ways to accomplish this. Here is a one liner:

    find . -type f -name "*" | xargs -n 1 -I {} sh -c 'file_full={}; file_bare=${file_full#./}; file=${file_bare##*/} prefix=${file_bare%%/*}; dir=${file_bare%/*}; echo mv ${file_full} ./${dir}/${prefix}${file}'
    

    Note, there is an echo in the final output. Remove the echo only if you are really happy with the solution and want this to be executed.