title: Replacing special characters in a shell script using sed
body: <p>I am trying to write a shell script that will replace whatever characters/strings I choose using sed.  My first attempt worked with the exception of special characters.  I have been trying to use sed to fix the special characters so that they too will be searched for or replaced.  I decided to simplify the script for testing purposed, and just deal with a single offending character.  However, I am still having problems.</p>
  
  <p>Edited Script</p>
  
  <pre><code>#! /bin/sh
  oldString=$1
  newString=$2
  file=$3
  
  oldStringFixed=$(echo "$oldString" | sed 's/\\/\\\\/g')
  oldStringFixed=$(echo "$oldStringFixed" | sed 's/\[/\\\[/g')
  oldStringFixed=$(echo "$oldStringFixed" | sed 's/\]/\\\]/g')
  oldStringFixed=$(echo "$oldStringFixed" | sed 's/\^/\\\^/g')
  oldStringFixed=$(echo "$oldStringFixed" | sed 's/\*/\\\*/g')
  oldStringFixed=$(echo "$oldStringFixed" | sed 's/\+/\\\+/g')
  oldStringFixed=$(echo "$oldStringFixed" | sed 's/\./\\\./g')
  oldStringFixed=$(echo "$oldStringFixed" | sed 's/\$/\\\$/g')
  oldStringFixed=$(echo "$oldStringFixed" | sed 's/\-/\\\-/g')
  
  sed -e "s/$oldStringFixed/$newString/g" "$file" &gt; newfile.updated
  mv newfile.updated "$file"#! /bin/sh
  </code></pre>
  
  <p>In case it is not clear, I am trying to search through oldString for the [ character, and replace it with an escaped version and assign the results to oldStringFixed (do I need the backticks for this?).  The bottom two lines are slightly modified versions of my original script that I believe works correctly.</p>
  
  <p>When I echo the fixed string, nothing is displayed, and sed outputs an error</p>
  
  <pre><code>sed: can't read [: No such file or directory
  </code></pre>
  
  <p>Can anyone explain what Is wrong with my first sed line?</p>
  
  <p>EDIT:</p>
  
  <p>Thanks to Jite, the script is working better.  However, I am still having a problem with replacing single quoted characters with spaces, i.e. ' *'.  The new version is above.</p>