For both macOS and Linux:
I'm not sure that the other answers address both Linux and macOS. If there are some that do, perhaps we can edit them to make that point clear.
Below is what I used in order to target both platforms.
Assume the file we want to perform the find/replace on contains the following text:
file.txt:
{{FROM}} hello world
Here is the script, replace.bash:
#!/bin/bash
PATTERN="s/{{FROM}}/HELLOWORLD/"
if [[ `uname -s`" == "Darwin" ]]; then
sed -i '' "$PATTERN" file.txt
echo Darwin
else
sed -i "$PATTERN" file.txt
echo Linuxxxx
fi
I later discovered that using single brackets and a single equals cooperated better between sh and bash:
replace.sh:
PATTERN="s/{{FROM}}/HELLOWORLD/"
if [ `uname -s` = "Darwin" ]; then
sed -i '' "$PATTERN" file.txt
echo Darwin
else
sed -i "$PATTERN" file.txt
echo Linuxxxx
fi
Your own cross-platform sed:
I can see how someone might replace $PATTERN with $1 and file.txt with $2 and actually be able to create a wrapper around sed that works on both platforms, such as:
ssed:
PATTERN="$1"
FILE=$2
if [ `uname -s` = "Darwin" ]; then
sed -i '' "$PATTERN" $FILE
else
sed -i "$PATTERN" $FILE
fi
$ chmod 755 ssed
$ ./ssed 's/{{FROM}}/jameswashere/' file
The file would then contain:
jameswashere hello world
What about recursive find/replace?
Now that we have our own platform-independent sed wrapper, we can use it, along with find, to loop through subdirectories and perform the find/replace on matching files:
$ find . -name "file" -exec ./ssed 's/{{FROM}}/that/g' {} \;
apple.stackexchange.com
as it's not generic enough for linux nor all devs.