Rajeev Rajeev - 1 year ago 70
Linux Question

Find files and print only their parent directories

I have the following commands. Wherever the

file is present, we need to print the parent directories (i.e
.) How can this be done?

$ cd /nfs//office/ && find . -name '.user.log'

Answer Source

Am I missing something here. Surely all this regex and/or looping is not necessary, a one-liner will do the job. Also "for foo in $()" solutions will fail when there are spaces in the path names.

Just use dirname twice with xargs, to get parent's parent...

# make test case
mkdir -p /nfs/office/hht/info
mkdir -p /nfs/office/wee1/info
touch /nfs/office/hht/info/.user.log
touch /nfs/office/wee1/info/.user.log

# parent's parent approach
cd /nfs//office/ && find . -name '.user.log' | xargs -I{} dirname {} | xargs -I{} dirname {}

# alternative, have find print parent directory, so dirname only needed once...
cd /nfs//office/ && find . -name ".user.log" -printf "%h\n"  | xargs -I{} dirname {}


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download