Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find files and print only their parent directories

I have the following commands. Wherever the .user.log file is present, we need to print the parent directories (i.e hht and wee1.) How can this be done?

$ cd /nfs//office/ && find . -name '.user.log'
./hht/info/.user.log
./wee1/info/.user.log
like image 601
Rajeev Avatar asked Mar 07 '12 07:03

Rajeev


1 Answers

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 {}

Produces

./hht
./wee1
like image 55
Adam Avatar answered Oct 20 '22 03:10

Adam