Shell – Find and rename files adding part of the path to filename

renameshell-script

I have a folder with two level of subfolders inside it. Inside the second subfolder, there is a jpg file. All the jpg have the same name: cover.jpg

Example:

/home/user/folder001/folderAAA/cover.jpg
/home/user/folder002/folderBBB/cover.jpg
[...]
/home/user/folder999/folderZZZ/cover.jpg

I need to find (and copy to a new folder) all cover.jpg files and rename them adding to its filename (as prefix) the name of the first and second subfolder.

Example:
After the intended operation, the content ot /home/user1/newfolder must be:

folder001_folderAAA_cover.jpg
folder002_folderBBB_cover.jpg
[...]
folder999_folderZZZ_cover.jpg

Best Answer

#! /bin/bash

target_dir_path="/copy/here"

for file in folder*/*/*.jpg; do
        l1="${file%%/*}"
        l2="${file#*/}"
        l2="${l2%%/*}"
        filename="${file##*/}"
        target_file_name="${l1}_${l2}_${filename}"
        echo cp "$file" "${target_dir_path}/${target_file_name}"
done

Remove the echo if it does what you want.

Related Question