Search code examples
linuxloopsrename

How to rename multiple files, contained in multiple sub-directories


I have a parent directory that contains multiple subdirectories, and each subdirectory has multiple files. For example:

Sub-directory_1
xyz1.fq.gz
xyz2.fq.gz

Sub-directory_2
abc1.fq.gz
abc2.fq.gz

etc.

I'd like to add the subdirectory name, as a prefix, to each file in each subdirectory.

I've been trying to do this with a loop that uses subdir and FILENAME, but can't get it right. Any help is appreciated.


Solution

  • You can use find command:

    $ find . -type f -exec bash -c 'mv {} "$(dirname {})/$(dirname {})_$(basename {})"' \;