0

I have something a directory like this

Main Directory
     SubDirectory
        SubsubDirectory1
           xx.jpg
           xx,jpg
        SubsubDirectory2
           xx.jpg
           xx,jpg
     SubDirectory
        SubsubDirectory1
           xx.jpg
           xx,jpg
        SubsubDirectory2
           xx.jpg
           xx,jpg
     SubDirectory
        SubsubDirectory1
           xx.jpg
           xx,jpg
        SubsubDirectory2
           xx.jpg
           xx,jpg

I want to copy all files in all SubsubDirectory1 to a destination directory

3

If the files have non-unique names, then

cp "Main Directory"/*/Subsubdirectory1/* destdir

would overwrite some of the files at the destination. This would also fail if there are thousands of matching pathnames.

To get around this, using GNU cp:

for pathname in "Main Directory"/*/Subsubdirectory1/*; do
    cp --backup=numbered "$pathname" destdir
done

This would create numbered backups of the files that would otherwise have been overwritten.

The same thing but using non-GNU cp:

for pathname in "Main Directory"/*/Subsubdirectory1/*; do

    # create first stab at destination pathname
    dest="destdir/${pathname##*/}"

    i=0
    while [ -e "$dest" ]; do
        # destination name exists, remove backup number from end of
        # pathname and replace with next one in the sequence
        i=$(( i + 1 ))
        dest="${dest%.~*~}.~$i~"
    done

    cp "$pathname" "$dest"
done
| improve this answer | |
  • Thanks a lot, the files have unique names, so I will try the first solution, and tell you if it works – Mostafa Hussein Jul 10 '18 at 9:31
1

Try this:

cp mainDir/*/SubsubDirectory1/* <destination_path>

Note: file names must be different.

| improve this answer | |
  • I will give it a try and give you feedback – Mostafa Hussein Jul 10 '18 at 9:30

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.