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!

2 Answers 2

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/ \; 
5
  • 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, 2014 at 7: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.
    – user234837
    Jul 22, 2014 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, 2014 at 21:18
  • execdir is a godsend
    – maxisme
    May 6, 2016 at 22:56
  • When you start hitting "find: The relative path ‘./node_modules/.bin’ is included in the PATH environment variable,": askubuntu.com/questions/621132/… Apr 9, 2019 at 9: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.

0

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.