Raj*_*eev 16 linux shell command
我有以下命令.无论.user.log文件存在于何处,我们都需要打印父目录(即hht和wee1.)如何做到这一点?
$ cd /nfs//office/ && find . -name '.user.log'
./hht/info/.user.log
./wee1/info/.user.log
Run Code Online (Sandbox Code Playgroud)
Ada*_*dam 17
我在这里错过了一些东西.当然,所有这些正则表达式和/或循环都不是必需的,单行程将完成这项工作.当路径名中有空格时,"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 {}
Run Code Online (Sandbox Code Playgroud)
产生
./hht
./wee1
Run Code Online (Sandbox Code Playgroud)
您可以使用操作的格式选项轻松完成此-printf操作find(请参阅man find)。
cd /nfs//office/ && find . -name '.user.log' -printf "%h\n"
./hht/info
./wee1/info
Run Code Online (Sandbox Code Playgroud)
从手册页:

%h\n 将在新行上打印每个文件的路径。
请注意,这-printf是仅限 GNU 的。它不适用于 macOS(BSD 系统)。