bash 脚本:如何将 find 命令结果保存到变量以便在 -exec 中使用它

发布于 2024-12-11 00:54:15 字数 128 浏览 0 评论 0原文

我想查找文件并将文件名保存到一个变量中,并在 -exec 中使用该变量以便用它进行一些计算,

因此例如每次查找返回一个文件名时,我都会在 -exec 中使用该文件名同时产生其他东西find命令找到这个文件

谢谢

I want to find files and save the file name to a variable and use this variable in -exec in order to do some calculations with it

so for example every time the find returns a file name I use that file name in -exec in order to produce something else at the same time find command finds this file

thanks

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

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

发布评论

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

评论(2

倦话 2024-12-18 00:54:15

然后不执行。

find -whatever |
while read filename; do
    Whatever you did in -exec before "$filename"
    Other thing "$filename"
done

不过,对于包含特殊字符的文件名来说,这并不可靠。

编辑:如果您想对 find 返回的命中执行多项操作,则可以使用 find -execxargs 以及:

find -whatever -exec sh -c 'whatever you did in -exec before {}; other thing {}' \;

或者您可以将输出修改为 shell 脚本并将其提供给 sh

find -whatever -printf 'mv %p destdir; ln -s destdir/%f %h\n' | sh

但如果您真的非常希望在 find 了解该文件,-exec 是可能是要走的路。 (我不清楚在什么情况下这将是一个有用的要求。也许你可以解释一下你想要实现什么?)

如果你想保留 find 返回的命中列表,这样你就可以find 完成后执行其他操作,使其输出命中(如上一个示例中所示),并将输出存储在文件中或通过管道将其传输到另一个命令(如第一个示例中所示)。

Then don't exec.

find -whatever |
while read filename; do
    Whatever you did in -exec before "$filename"
    Other thing "$filename"
done

This is not robust with file names containing special characters, though.

Edit: If you want to do multiple things to the hits returned by find, this is certainly possible with find -exec or xargs as well:

find -whatever -exec sh -c 'whatever you did in -exec before {}; other thing {}' \;

Or you can mangle the output into a shell script and feed it to sh:

find -whatever -printf 'mv %p destdir; ln -s destdir/%f %h\n' | sh

But if you really, truly want the action to happen as soon as find learns about the file, -exec is probably the way to go. (I'm not clear on under what circumstances this would be a useful requirement. Perhaps you can explain what you want to achieve?)

If you want to keep the list of hits returned by find so you can do additional things after find finishes, make it output the hits like in the last example, and store the output in a file or pipe it to another command like in the first example.

动听の歌 2024-12-18 00:54:15

“我想获取每个文件名并在内部搜索信息,例如行中的字符串、句子” - 好的乔纳森,这就是您应该在问题中说的:-)

答案:

find /dir -iname "*whatever*" | xargs grep 'text'

会找到文本目录 /dir 下每个文件 *whatever* 中的“文本”。

"I want to take each file name and search inside for information, for example strings in lines, sentences" - OK Jonathan, that's what you should have said in your question :-)

Answer:

find /dir -iname "*whatever*" | xargs grep 'text'

will find text "text" in every file *whatever* under directory /dir.

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