Search code examples
bashfilecopyzshfile-copying

Copy specific files from subdirectories into one directory


I have a directory:

❯ find ./images -name *150x150.jpg
./images/2060511653921052666.images/thumb-150x150.jpg
./images/1777759401031970571.images/thumb-150x150.jpg
./images/1901716489977597520.images/thumb-150x150.jpg
./images/2008758225324557620.images/thumb-150x150.jpg
./images/1988762968386208381.images/thumb-150x150.jpg
./images/1802341648716075239.images/thumb-150x150.jpg
./images/2051017760380879322.images/thumb-150x150.jpg
./images/1974813836146304123.images/thumb-150x150.jpg
./images/2003120002653201215.images/thumb-150x150.jpg
./images/1911925394312129508.images/thumb-150x150.jpg
(...)

I would like to copy all those files (thumb-150x150.jpg) into one directory.

❯ find ./images -name *150x150.jpg -exec cp {} ./another-directory \;

But of course every file will be overwritten by the next one.

So how could I copy them to either:

1) 1.jpg, 2.jpg, 3.jpg... etc

or

2) use the subdirectory id (./images/2060511653921052666.images/thumb-150x150.jpg) as the target filename (2060511653921052666.jpg in this example) ?


Solution

  • you can use loop:

    i=1
    find ./images -name *150x150.jpg | while read line; do
            cp $line /anotherdir/$i.jpg
            i=$[i+1]
    done