linux - 查找文件并仅打印其父目录

标签 linux shell command

我有以下命令。无论 .user.log 文件在哪里,我们都需要打印父目录(即 hhtwee1。)如何做到这一点?

$ 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/

相关文章:

c# - 单击时如何使命令不禁用按钮

c++ - 以附加模式打开管道

linux - 网络/url 日志记录 Linux

Python 脚本分发

bash - 如何在匹配正则表达式的第一行之后获取文件的一部分

linux - 如何编写shell脚本来为文件名中具有相同字符串的文件创建zip文件

java - 如何在Java中执行 native 命令?

php - 从 PHP 写入十六进制到串口

image - 如何自动删除7天前创建的docker镜像?

android - 这个脚本实际上做了什么?