5

I'm trying to find files containing *.nef and move them to a subdirectory name NEF of the folder in which the file is found.

I've started testing with the following command, but this always copies to my current directory, which is my home folder.

find testfolder/*.nef -exec mv NEF \;

In the man find section i've read about using -execdir, but using this instead of -exec still has the same result.

So the question is: how can i dynamically assume the currently found directory and mv found files to a sub-directory folder named NEF? (which does not yet exist)

Thanks in advance!

Sudheer
  • 5,113
  • 4
  • 24
  • 27
fairlynuts
  • 63
  • 1
  • 5

2 Answers2

6

You were right in considering -execdir. Something simple like the below should work

find testfolder/ -name '*.nef' -execdir mkdir -p NEF \; -execdir mv {} NEF/ \; 
  • Wow, such a clean command which works perfectly. The prior solution didn't quite work with folders containing spaces, but this one does. Thanks a lot. – fairlynuts Jul 22 '14 at 07:34
  • @fairlynuts Glad it helped. Also note that the original syntax wouldn't have moved files if the directory already existed. Not sure whether that's requisite in the question, but added the -p, so they get moved anyway. –  Jul 22 '14 at 21:04
  • Actually, I didn't blindly copy your solution, I tried it first by typing it over so I got a grasp of what I was doing. All of the sudden I saw that there was only one file being copied to a created folder 'NEF' and the rest was ignored, indeed with the error 'cannot create directory', but I was missing the -p option which you already gave. After having completed the mv work, I can now say that this worked perfectly, which indeed includes the -p option. Thanks! – fairlynuts Jul 23 '14 at 21:18
  • execdir is a godsend – maxisme May 06 '16 at 22:56
  • When you start hitting "find: The relative path ‘./node_modules/.bin’ is included in the PATH environment variable,": https://askubuntu.com/questions/621132/why-using-the-execdir-action-is-insecure-for-directory-which-is-in-the-path/1109378#1109378 – Ciro Santilli OurBigBook.com Apr 09 '19 at 09:08
2

Try:

find  testfolder/ -iname "*.nef" -exec bash -c 'mkdir $(dirname "{}")/NEF ; mv "{}" $(dirname "{}")/NEF/' \;

dirname used to extract path from result then use it to make new subdirectory before moving the file.

user.dz
  • 48,105