Hello I have a bunch of folders with several images (jpg and png) at the same directory level (./ParentDirectory/contents/1680x1050.png for example) called the same (1680x1050.jpg or 1680x1050.png) on different subdirectories,

I want to know if it's possible to use the find command to copy this files to a different directory (e.g. ./Something/) keeping the name but adding the parent name to the file name so at the end they are as ./Something/ParenDirectory_1680x1050.jpg and ParenDirectory_1680x1050.png.


After cding to the parent directory of ParentDirectory, run:

find ParentDirectory -type f \( -name "1680x1050.png" -o -name "1680x1050.jpg" \) \
  -exec sh -c 'cp "$1" "Something/${1%%/*}_${1##*/}"' sh {} \;

In the -exec part where a new shell process is executed for each png or jpg found, the path to the image {} is passed as argument $1 to the shell script.

In the cp command the target filename is put together and ${1%%/*} is used to get the parent directory name removing the longest suffix pattern (everything after the first /) and ${1##*/} is used to get the filename part removing the longest prefix pattern (all characters until the last /).

To achieve the same result executing only one shell process for all images found, you could use

find ParentDirectory -type f \( -name "1680x1050.png" -o -name "1680x1050.jpg" \) \
  -exec sh -c 'for i; do cp "$i" "Something/${i%%/*}_${i##*/}"; done' sh {} +

and loop through all filename arguments in the script with a for-loop.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.