Bash – Shell Script: Copy first file from multiple folders into one single folder

bashfile-copy

In a directory, I have hundreds of sub-directories. Each sub-directory has hundreds of jpg pictures. If the folder is called "ABC_DEF", the files inside the folder will be called "ABC_DEF-001.jpg", "ABC_DEF-002.jpg", so on and so forth.

For example:

---Main Directory
------Sub-Directory ABC_DEF
----------ABC_DEF-001.jpg
----------ABC_DEF-002.jpg
------Sub-Directory ABC_GHI
----------ABC_GHI-001.jpg
----------ABC_GHI-002.jpg

From each of the sub-directory I want to copy only the first file, e.g., the file with the extension -001.jpg – to a common destination folder called DESTDIR.

I have changed the code given here to suit my use case. However, it always prints the first directory along with the filenames and I am not able to copy the files to the desired destination. The following is the code:

DIR=/var/www/html/beeinfo.org/resources/videos/
find "$DIR" -type d |
while read d;
do
    files=$(ls -t "$d" | sed -n '1h; $ { s/\n/,/g; p }')
    printf '%s,%s\n' "$files";
done

How can I fix this code?

Best Answer

Why find when all files are in directories of the same depth?

cd "$DIR"
cp */*-001.jpg /destination/path
Related Question