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

2 Answers 2

5

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
1
  • Thanks a lot, the files have unique names, so I will try the first solution, and tell you if it works Commented Jul 10, 2018 at 9:31
1

Try this:

cp mainDir/*/SubsubDirectory1/* <destination_path>

Note: file names must be different.

1
  • I will give it a try and give you feedback Commented Jul 10, 2018 at 9:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .