bash:find 命令中的复杂测试

发布于 2024-09-24 04:52:02 字数 178 浏览 0 评论 0原文

我想做类似的事情:

find . -type f -exec test $(file --brief --mime-type '{}' ) == 'text/html' \; -print 

但我无法找出引用或转义要测试的参数的正确方法,尤其是 '$(' ... ')' 。

I would like to do something like:

find . -type f -exec test $(file --brief --mime-type '{}' ) == 'text/html' \; -print 

but I can't figure out the correct way to quote or escape the args to test, especially the '$(' ... ')' .

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光匆匆的小流年 2024-10-01 04:52:02

您不能简单地将参数转义以将其传递给 find

任何 shell 扩展都会在 find 运行之前发生。 find 不会通过 shell 传递其参数,因此即使您转义 shell 扩展,所有内容都将被简单地视为 test 命令的文字参数,而不是由正如你所期望的那样。

实现您想要的效果的最佳方法是编写一个简短的 shell 脚本,该脚本将文件名作为参数,然后使用 -exec

find . -type f -exec is_html.sh {} \; -print

with is_html.sh

#!/bin/sh

test $(file --brief --mime-type "$1") == 'text/html'

如果您确实希望将所有内容都放在一行中,而不使用单独的脚本,则可以直接从 find 调用 sh

find . -type f -exec sh -c 'test $(file --brief --mime-type "$0") == "text/html"' {} \; -print

You cannot simply escape the arguments for passing them to find.

Any shell expansion will happen before find is run. find will not pass its arguments through a shell, so even if you escape the shell expansion, everything will simply be treated as literal arguments to the test command, not expanded by the shell as you are expecting.

The best way to achieve what you want would be to write a short shell script, which takes the filename as an argument, and use -exec on that:

find . -type f -exec is_html.sh {} \; -print

with is_html.sh:

#!/bin/sh

test $(file --brief --mime-type "$1") == 'text/html'

If you really want it all on one line, without using a separate script, you can invoke sh directly from find:

find . -type f -exec sh -c 'test $(file --brief --mime-type "$0") == "text/html"' {} \; -print
故人的歌 2024-10-01 04:52:02

尽管可以将其变成一个被广泛引用的声明,但更冗长一些通常更容易且更清晰:

$ find . -type f -print0 | xargs -0 file --mime-type | ↷
   grep ':[^:]*text/html
| sed 's,:[^:]*text/html,,'

Although it may be possible to turn it into one wildly quoted statement, it is often easier - and more clear - to be a little more verbose:

$ find . -type f -print0 | xargs -0 file --mime-type | ↷
   grep ':[^:]*text/html
| sed 's,:[^:]*text/html,,'
心清如水 2024-10-01 04:52:02

请改用“{}”,例如,仅列出文件类型:

find * -maxdepth 0 -exec file "{}" \;

Use "{}" instead, for an example this simply lists file types:

find * -maxdepth 0 -exec file "{}" \;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文