打印"find" linux命令找到匹配项的目录 [英] Print the directory where the 'find' linux command finds a match

查看:435
本文介绍了打印"find" linux命令找到匹配项的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆目录;其中一些包含".todo"文件.

I have a bunch of directories; some of them contain a '.todo' file.

/storage/BCC9F9D00663A8043F8D73369E920632/.todo
/storage/BAE9BBF30CCEF5210534E875FC80D37E/.todo
/storage/CBB46FF977EE166815A042F3DEEFB865/.todo
/storage/8ABCBF3194F5D7E97E83C4FD042AB8E7/.todo
/storage/9DB9411F403BD282B097CBF06A9687F5/.todo
/storage/99A9BA69543CD48BA4BD59594169BBAC/.todo
/storage/0B6FB65D4E46CBD8A9B1E704CFACC42E/.todo

我希望使用"find"命令仅向我显示该目录,就像这样

I'd like the 'find' command to print me only the directory, like this

/storage/BCC9F9D00663A8043F8D73369E920632
/storage/BAE9BBF30CCEF5210534E875FC80D37E
/storage/CBB46FF977EE166815A042F3DEEFB865
...

这是我到目前为止的内容,但它也列出了".todo"文件

here's what I have so far, but it lists the '.todo' file as well

#!/bin/bash
STORAGEFOLDER='/storage'
find $STORAGEFOLDER -name .todo  -exec ls -l {} \;

应该是愚蠢的,但是我正在放弃:(

Should be dumb stupid, but i'm giving up :(

推荐答案

仅打印目录名称,请使用-printf '%h\n'.还建议您用双引号将变量引起来.

To print the directory name only, use -printf '%h\n'. Also recommended to quote your variable with doublequotes.

find "$STORAGEFOLDER" -name .todo -printf '%h\n'

如果要处理输出:

find "$STORAGEFOLDER" -name .todo -printf '%h\n' | xargs ls -l

或使用带有进程替换的循环来使用变量:

Or use a loop with process substitution to make use of a variable:

while read -r DIR; do
    ls -l "$DIR"
done < <(exec find "$STORAGEFOLDER" -name .todo -printf '%h\n')

该循环实际上一次会处理一个目录,而在xargs中,目录一次就会通过ls -l传递.

The loop would actually process one directory at a time whereas in xargs the directories are passed ls -l in one shot.

要确保一次只处理一个目录,请添加uniq:

To make it sure that you only process one directory at a time, add uniq:

find "$STORAGEFOLDER" -name .todo -printf '%h\n' | uniq | xargs ls -l

while read -r DIR; do
    ls -l "$DIR"
done < <(exec find "$STORAGEFOLDER" -name .todo -printf '%h\n' | uniq)

如果您没有bash并且不介意在循环外保留对变量的更改,则可以使用管道:

If you don't have bash and that you don't mind about preserving changes to variables outside the loop you can just use a pipe:

find "$STORAGEFOLDER" -name .todo -printf '%h\n' | uniq | while read -r DIR; do
    ls -l "$DIR"
done

这篇关于打印"find" linux命令找到匹配项的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆