How to search and replace without changing ownership

I found this command line example and replaced the example:

find . -type f -print0 | xargs -0 sed -i 's/find/replace/g' 

It worked great, except that it changed the date and ownership of the file to EVERY file that he looked at, even those that did not contain search text.

What is the best solution to this problem?

+4
source share
3 answers

Using the -c option (if you're on Linux) should force sed to retain ownership. When you use this command, it actually overwrites each file, even if it does not make changes to files that do not contain find .

+4
source

The easiest way to fix this would be to just execute sed on the files if you first contain the text with grep:

 find . -type f | while read file; do grep -q find $file && sed -i 's/find/replace/g' $file done 

This requires reading each file twice (in the worst case), so it can be a little slower. I would hope, however, that your OS should store the file in its disk cache, so you should not see much of the slowdown, since this process is definitely related to I / O and not to the CPU.

+3
source

Some versions of sed distribution (namely RedHat and family) have added the -c option, which does this, in which case see @Isaac answer.

But for those with unpatched GNU sed, the easiest way I've found is to simply replace perl, which overwrites files similar to sed -c when they are available. The following commands are basically equivalent:

 sed -ci 's/find/replace/' perl -pi -e 's/find/replace/' 

Just don’t worry too much and do perl -pie ; for example, sed -ie instead of interpreting as another parameter, it will use e as an argument for -i and use it as a suffix to back up the source file. See perldoc perlrun .

Perl's regex parsing is slightly different than sed (better, imo) for more complex things: generally speaking, use less backslashes.

+1
source

Source: https://habr.com/ru/post/1306512/


All Articles