-1

I have three levels of folders like main, sub-1 and sub-2. my main folder has lot of sub-1 folders and each sub-1 has lot of sub-2 folder with JPG images inside.

I am trying to find and copy JPG files from sub-2 into its parent sub-1 folder being FROM main folder.

So my current solution is to go to each sub-1 folder and use this script to find and copy all JPG from sub-2 folder into its parent sub-1 folder.

find . -type f -name "*.jpg" -exec cp {} ./ \;

Why this script below not working? how do I find and copy JPG from main folder without going into the each sub-1 folder?

Update I tried this script:

find . -type f -name "*.jpg" -exec cp {} ../ \;

but this brings all the images to the main folder instead of the sub-1 folder.

Sam
  • 195
  • 1
  • 18

1 Answers1

0

.. refers to the parent directory of your current working directory.

To strip off one level of directory structure from the end, try

find . -type f -name "*.jpg" -exec sh -c 'for p; do
    cp "$p" "${p%/*/*}"
  done' _ {} +

The parameter expansion ${p%pattern} produces the value of p with the shortest possible match on pattern removed from the end of it (or simply returns the original value when the pattern doesn't match).

Because the parameter expansion needs to be evaluated at the time the file name is set, we wrap it in sh -c '...' and for efficiency, we wrap the operation in a for loop so that find can pass in multiple files to a single shell invocation (hence + instead of \; at the end).

The _ is just a placeholder which gets assigned to $0 which isn't used at all here.

In the less general case, if you just have a single destination folder, you can hard-code it directly, of course:

find . -type f -name "*.jpg" -exec cp -t sub-1 {} +

Unfortunately, cp -t is a GNU extension; if your OS doesn't have it, you have to reorganize to something more similar to the above command.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Even though I did not understand most technical terms yet, you saved my time a lot. it worked thanks genius. I will try to understand these soon – Sam Aug 30 '21 at 09:57
  • now this command finds JPGs from my MAIN folder, what if there is a parent folder for that MAIN folder and what should I need add or change in this command to find from new parent folder? – Sam Aug 31 '21 at 06:51
  • You continue to ask questions with rather roundabout requirements. As already indicated in this answer, the parent folder of `.` is `..`. Perhaps also read [What exactly is current working directory?](https://stackoverflow.com/questions/45591428/what-exactly-is-current-working-directory) – tripleee Aug 31 '21 at 06:54