Find and exec in found folder

6,175

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.

Share:
6,175

Related videos on Youtube

fairlynuts
Author by

fairlynuts

Updated on September 18, 2022

Comments

  • fairlynuts
    fairlynuts almost 2 years

    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!

  • Admin
    Admin almost 10 years
    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.
  • Admin
    Admin almost 10 years
    @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.
  • Admin
    Admin almost 10 years
    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!
  • Admin
    Admin about 8 years
    execdir is a godsend
  • Admin
    Admin about 5 years
    When you start hitting "find: The relative path ‘./node_modules/.bin’ is included in the PATH environment variable,": askubuntu.com/questions/621132/…