csh find command: how to get the upmost directory

175 Views Asked by At

I'm looking for a csh command that searches directories only.
I know the name of the directory (MY_DIR), however I totally ignore how far below the current directory they are.

I'd like the command :

  • gave no error messages in case it ended up to not accessible directories;
  • gave a void string in case it didn't find the directory;
  • quit the searching as soon as it found the first occurrence of the directory;
  • gave priority to the upmost directories.

I thought find was the right command and I used it like this:

find . -type d ! -perm -a+r -prune -o \( -type d -o -type l \) -name MY_DIR -print -quit

being the directories structure as follows

DIR_A0/DIR_A1/DIR_A2/MY_DIR  
DIR_B0/DIR_B1/MY_DIR

the outcome was:

DIR_A0/DIR_A1/DIR_A2/MY_DIR

and I'd rather like to get:

DIR_B0/DIR_B1/MY_DIR

I wonder if someone could give me any advice on how to sort this thing out.

Many thanks in advance

1

There are 1 best solutions below

0
On

The "upmost" directory is the one with the fewest / characters.

Borrowing from this answer, we can get this by piping the output to awk:

find . -name MY_DIR |\
  awk -F/ 'BEGIN { depth=100; } depth > NF { depth=NF; dir=$0; } END { print dir }'

Note that you'll want to remove the -quit option from your find command. AFAIK there is no way to do this with just find, since find simple finds paths as they are stored on the filesystem (which can be in any order). You'll need to get a full list first.