使用 xargs sed 查找和替换 - 我可以将结果保存到文件中吗?

发布于 2025-01-01 08:02:18 字数 371 浏览 4 评论 0原文

我的代码将 'foo' 的所有实例替换为 'bar' :

find . -type f |
xargs grep 'foo' -l |
xargs sed -i 's|foo|bar|g'

我想将修改后的文件列表保存到文本文档中。是否可以?

编辑:

这是对我有用的最终代码:

find . -type f -print0 |
xargs -0 grep 'foo' -l |
tee result.txt |
xargs -0 sed -i 's|foo|bar|g'

不确定这是否是最快的方法,但对于几千个文件,此方法与其他建议方法之间的速度差异可能非常小。

My code to replace all instances of 'foo' with 'bar' :

find . -type f |
xargs grep 'foo' -l |
xargs sed -i 's|foo|bar|g'

I'd like to save a list of the modified files to a text document. Is it possible?

EDIT :

This is the final code that worked for me :

find . -type f -print0 |
xargs -0 grep 'foo' -l |
tee result.txt |
xargs -0 sed -i 's|foo|bar|g'

Not sure whether this is the quickest way, but for a few thousand files the difference in speed between this and other suggested methods is probably very small.

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

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

发布评论

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

评论(1

梦在深巷 2025-01-08 08:02:18

看起来 xargs 的使用毫无用处,就像经常与 find 结合使用一样。

find . -type f -exec grep 'foo' -l {} ";" -exec sed -i 's|foo|bar|g' {} ";" -ls > file.lst

请小心使用,因为我没有测试过。我不确定您是否想更改文件名列表或文件内容。由于您使用 grepsed 进行搜索,我认为仅使用 sed 就足够了:

find . -type f -exec sed -i 's|foo|bar|g' {} ";" -ls > file.lst

Looks like a useless use of xargs, as often in combination with find.

find . -type f -exec grep 'foo' -l {} ";" -exec sed -i 's|foo|bar|g' {} ";" -ls > file.lst

Use it with care, since I didn't test it. I'm not sure, whether you like to change the list of filenames, or the file content. Since you search with grep and sed, I think only working with sed should be sufficient:

find . -type f -exec sed -i 's|foo|bar|g' {} ";" -ls > file.lst
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文