find & sed -i work fine. Now need -i workaround for old OS.

I have a script that does a search and replace on a tree using find, xargs and sed that looks something like this.

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

Now this works fine on new versions on Linux but I need to make the script work on an old RAQ550 that has an older version of Gnu sed that doesn't support the "-i" option in sed that changes files in-place instead of writing to standard output.

Does anyone know any simple, neat workarounds to achieve the same effect without "-i"?

The command above is a simplified version of what I have so simply not using "find" is not the solution I am looking for. Also the script has to handle file names with spaces hense the "xargs -0" stuff.

OK I finally resolved this myself so I am posting the solution in case it helps anyone else out there.

It is possible to use the -i switch of xargs to pass the same file name to several commands quoted in a list. This command should be safe with filenames containing
spaces, which is more than can be said for most shell script examples I've seen on the subject! This is why all the file name references are quoted. Because the whole line is itself quoted, the quotes within have to be escaped with the backslash.

tmpFile="/tmp/sedswap$RANDOM"; find . -type f -print0 | xargs -0 -i bash -c "sed 's/fromthis/tothis/g' \"{}\" > \"$tmpFile\"; rm -f \"{}\"; mv \"$tmpFile\" \"{}\";"

The random temporary file name is just to greatly reduce the risk of any clashes if two instances of this command run concurrently.

$RANDOM is helpful, but there's still a 1/32000 chance that you'll have a clash within the next instant. You can also try using $$, because that is the PID, which is always increasing (up to 64k) until it restarts. But it will be a while before it cycles around, so you're (often) pretty safe using that.

Sendmail, for example, does even more elaborate filename generation for the files in its mailqueue because creating thousands of files in a short period if time is pretty easy for it. So you won't see it using such a simple algorithm. But it works for many shell script situations.
-Mike

Wow, I never new it was so easy to get the PID number from within a script!

Thanks :slight_smile: