Skip to content

Instantly share code, notes, and snippets.

@samisalkosuo
Created December 10, 2014 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samisalkosuo/e05c3df8188698fabdfe to your computer and use it in GitHub Desktop.
Save samisalkosuo/e05c3df8188698fabdfe to your computer and use it in GitHub Desktop.
Change string in file.
#!/bin/sh
#change string in file
if [[ $# -ne 3 ]]; then
echo "Wrong number of arguments"
echo "Usage: $0 FILE FROMSTRING TOSTRING"
exit 1
fi
SED_FILE=$1
FROMSTRING=$2
TOSTRING=$3
TMPFILE=$SED_FILE.tmp
#escape to and from strings
FROMSTRINGESC=$(echo $FROMSTRING | sed -e 's/\\/\\\\/g' -e 's/\//\\\//g' -e 's/&/\\\&/g')
TOSTRINGESC=$(echo $TOSTRING | sed -e 's/\\/\\\\/g' -e 's/\//\\\//g' -e 's/&/\\\&/g')
sed -e "s/$FROMSTRINGESC/$TOSTRINGESC/g" $SED_FILE > $TMPFILE && mv $TMPFILE $SED_FILE
if [ ! -f $TMPFILE ]; then
exit 0
else
echo "ERROR: Something went wrong."
exit 2
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment