Skip to content

Instantly share code, notes, and snippets.

@duggan
Last active August 11, 2024 13:48
Show Gist options
  • Save duggan/5765629 to your computer and use it in GitHub Desktop.
Save duggan/5765629 to your computer and use it in GitHub Desktop.
Using sed to to find/replace in a file in a portable way.
#!/bin/sh
# Usage: replace "foo" "bar" "/etc/omg.conf"
replace() {
local pattern=$1
local replacement=$2
local file=$3
local tempfile="$(mktemp -t temp.XXXXX)"
sed "s/$pattern/$replacement/" ${file} > ${tempfile} && mv ${tempfile} ${file}
}
@falenn
Copy link

falenn commented Oct 8, 2015

Great! Thanks

@bartagabor
Copy link

sed -i does in place replace, no need for manual rename

@john8329
Copy link

sed -i does in place replace, no need for manual rename

but then it's not portable
https://stackoverflow.com/questions/4247068/sed-command-with-i-option-failing-on-mac-but-works-on-linux

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment