Rename files of the same name in multiple subdirectories

I have multiple directories with unique identifying names. Within each of these are further identicle subdirectories generated by an automated analysis software. Within one of these subdirectories is a file I want to pick out and move to a unique dir, naming them after their respective parent directory.

For example:

Directories = A001 A002 A003 A004

Subdirectories = A001/files A002/files A003/files A004/files

Identical file name in each subdirectory = A001/files/aseg.mgz A002/files/aseg.mgz etc etc

Unique new directory = collated_aseg

I want to move all the aseg.mgz files into the collated_aseg dir and rename them so they are identifiable as coming from the original parent directory: e.g. A001_aseg.mgz (or equivalent).

I have looked at similar issues (Rename a file to parent directory's name in terminal) - however, these have only one layer of directory, whereas my issue has two. I was wondering whether this could be easily done.

1 Answer

Since the intermediate directory name is apparently constant, it should be straightforward with a shell loop:

for d in A???; do echo cp "$d/files/aseg.mgz" "collated_aseg/$d.mgz"; done

Remove the echo once you are happy that it's doing the right thing. The collated_aseg directory must already exist. Replace cp with mv if you really want to rename (move) rather than copy.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like