我有以下命令。无论 .user.log
文件在哪里,我们都需要打印父目录(即 hht
和 wee1
。)如何做到这一点?
$ cd /nfs//office/ && find . -name '.user.log'
./hht/info/.user.log
./wee1/info/.user.log
最佳答案
我是不是漏掉了什么。当然,所有这些正则表达式和/或循环都不是必需的,一行代码就可以完成这项工作。当路径名中有空格时,“for foo in $()”解决方案也会失败。
只需将 dirname 与 xargs 一起使用两次,即可获取父级的父级......
# 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 {}
生产
./hht
./wee1
关于linux - 查找文件并仅打印其父目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9597433/