Page 1 of 1

Finding the directory of a file

Posted: Mon Aug 13, 2007 6:53 am
by Ollie Saunders
I'm iterating over a bunch of directories looking for files called Interface.php

Code: Select all

for x in $(find . -name 'Interface.php')
do echo $x
done
I want to find out what the name of directory each Interface.php is it. So if it is in /foo/bar/Interface.php I want to get "bar" and put it in a variable.

This is what I'm doing at the moment but there's probably a better way.

Code: Select all

for x in $(find . -name 'Interface.php')
do  php -r '
        $split = explode("/", $argv[1]);
        $last = $split[count($split) - 2];
        exit($last);
    ' $x; 
    last=${?:1}
    echo $last
done

Posted: Mon Aug 13, 2007 7:43 am
by Chris Corbyn
Have a look at the basename and dirname commands in UNIX.

Sadly basename doesn't implement a pipe interface so you can't do this:

/var/log/messages <--- want "log" back

Code: Select all

dirname /var/log/messages | basename  #Gives error
basename `dirname /var/log/messages` #works

Posted: Mon Aug 13, 2007 8:04 am
by volka
but this

Code: Select all

find . -name 'Interface.php' -exec dirname {} \; | while read d; do dirname $d; done

Posted: Mon Aug 13, 2007 8:34 am
by Ollie Saunders
I only want the last directory name btw. Not the whole path.
I wrote:So if it is in /foo/bar/Interface.php I want to get "bar" and put it in a variable.

Posted: Mon Aug 13, 2007 8:54 am
by feyd

Code: Select all

find . -name "Interface.php" | while read d; do basename `dirname $d`; done
works for me.

Posted: Mon Aug 13, 2007 8:58 am
by volka
oops typo, replace one dirname by basename in my script.

Code: Select all

find . -name 'Interface.php' -exec dirname {} \; | while read d; do basename $d; done
If feyd has tested his version take it, mine is untested.

Posted: Mon Aug 13, 2007 9:20 am
by feyd
I'll clarify that mine works on OS X. :)

Posted: Mon Aug 13, 2007 10:20 am
by Chris Corbyn
I'm not sure what the while() is needed for:

Code: Select all

for i in $(find . -name 'Interface.php'); do basename `dirname $i`; done

Posted: Mon Aug 13, 2007 11:26 am
by volka
And I could say: I'm not sure what the for() is needed for. ;)

Posted: Mon Aug 13, 2007 1:12 pm
by Chris Corbyn
volka wrote:And I could say: I'm not sure what the for() is needed for. ;)
:lol: That dawned on me about 10 seconds after I posted my version. It's been a long day 8O