大网数据广告活动
服务器运维问答

Dropping the -print0 and -0 flags from find and xargs

· 52CE 我爱测

Almost 10 years ago, I asked this question use SED recursively in linux? and got this useful command find . -type f -print0 | xargs -0 sed -i 's/regex_search_term/replace_term/g' I decided to learn more about the find , xargs and…

问题原文

原帖链接 · learningtech · CC BY-SA 4.0

Almost 10 years ago, I asked this question

use SED recursively in linux?

and got this useful command find . -type f -print0 | xargs -0 sed -i 's/regex_search_term/replace_term/g'

I decided to learn more about the find, xargs and sed statement. On Ubuntu 18.04 in bash version 4.4.20(1)-release, I can simplify the statement to this:

find . -type f -print | xargs sed -i 's/regex_search_term/replace_term/g'

Which can then be simplified again to this:

find . -type f | xargs sed -i 's/regex_search_term/replace_term/g'

So my question is, are there any drawbacks to not using the -print0 flag with the -0 flag of find and xargs respectively? And are there any drawbacks to dropping the -print flag altogether? Are they explicitly used for compatibility with different unix like systems?

已采纳解答

原帖链接 · Gordon Davisson · CC BY-SA 4.0

The versions that don't use -print0 and xargs -0 will get confused by a number of rare-but-legal characters in filenames, including spaces, tabs, newlines, quotes, and backslashes. A zero byte (the ASCII NUL character) is the only thing that cannot occur in a file path, so using it as a delimiter avoids these potential problems.

But there's actually a simpler way. Modern versions of find have a -exec ... + primary that does essentially the same thing as xargs, directly in the find command:

find . -type f -exec sed -i 's/regex_search_term/replace_term/g' {} +

This doesn't have all of the options that xargs has, so if you need something other than the usual collect-names-and-run-it you should still use -print0 | xargs -0.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-12-07)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。