2

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?

  • 4
    What happens with a file having spaces in its name? or newlines? – A.B Dec 7 '19 at 17:15
6

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.