spyderman4g63
spyderman4g63

Reputation: 4309

How to use 'find' to return parent directory

I am using find to locate a file, but I want to only return the path to the parent directory of the file.

find /home/ -name 'myfile' -type f

That returns a list of the full path to all of the file matches, but I want to

Upvotes: 8

Views: 11373

Answers (6)

Vijay
Vijay

Reputation: 67221

find /home/ -name 'myfile' -type f|awk -f"/" '{print $(NF-1), "/",$NF}'

Upvotes: 1

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

If you want to execute something in the directory of the found file you may want to use -execdir action.

find /home/ -name 'myfile' -type f -print -execdir chmod -c 700 . \;

Upvotes: 4

Simon
Simon

Reputation: 1207

The -printf action lets you extract lots of information about the file. '%h' is the directive to get the path part of the file name.

find /home/ -name 'myfile' -type f -printf '%h\n'

Upvotes: 11

Karoly Horvath
Karoly Horvath

Reputation: 96258

cd /home; find . -name 'myfile' -type f | sed "s/\/[^/]*$//" | cut -d "/" -f2- | sort -u

Upvotes: 0

jim mcnamara
jim mcnamara

Reputation: 16379

one way of many:

find /   -name 'myfile' -type f -exec dirname {} \;

Upvotes: 25

jman
jman

Reputation: 11606

find /home/ -name 'myfile' -type f | rev | cut -d "/" -f2- | rev | sort -u

Upvotes: 0

Related Questions