linux - Finding subdirectories inside all directories with the same name

07
2014-07
  • iammilind

    I want to run a command to:

    1. Find all directories named "inc" under a folder "X".
    2. List all the subdirectories under each "X/.../inc/".
    3. Redirect the output to a file named "list"

    I tried various combinations of the below command, without success:

    $ find X/ -name "inc" -print | xargs find {} -type d > list
    find: path must precede expression
    

    How can I do this?

  • Answers
  • Daniel Andersson

    find can do this all by itself:

    find X -path '*/inc/*' -type d > list
    

    Read the -path part of man find for more info.

    As I mentioned quickly in a comment: if you store the directories line separated in a text file, directory names containing newlines won't be unambiguously representable. If you are certain that directories don't contain newlines, that's OK. Just a general remark.

  • slhck

    Here's a handy one-liner:

    find X -type d -name "inc" -exec sh -c 'find {} -type d' \; > list
    

    It runs find on each of the first find results. The exec option can also take a minimal shell command, in which – as I said – {} is replaced with each directory of the first find.

    The second find will, per your request, "list all subdirectories" of the first results, including the inc directory. If you don't want that itself in the output, let the second find at least output folders of depth 1.

    find X -type d -name "inc" -exec sh -c 'find {} -mindepth 1 -type d' \; > list
    

    We'll then just redirect the command's stdout into list.

  • iammilind

    Alright I have found the answer to simulate this nested find:

    find X/ -type d | grep "/inc/" > list
    
  • Prince John Wesley

    Try this:

       find path-of-x -path '*/inc/*' -type d > list
    

  • Related Question

    linux - Find all files on server with 777 permissions
  • Questioner

    I'm looking for a Linux command to go through all the directories on my server and find all files with 777 permission. The output would be a list of all those files with full path.


  • Related Answers
  • jheddings

    Just like your last question, use find:

    find / -type f -perm 0777
    
  • Kai

    And if you like to find all files without Permission 0777 then just enter a ! before the perm, e.g.

    find / -type f ! -perm 0777

  • altmas5

    You can also change the permissions or ownership of all those files resulting from the find execution using the -exec option to avoid change them manually. Exempli gratia: In a web server you could need to grant the group to write files:

    find / -type f -perm 0777 -exec chmod 775 {} \; -exec chgrp -R www {} \;
    
  • knittl

    it's as easy as:

    find / -perm 0777
    

    if you only want to match files, use this instead:

    find / -type f -perm 0777