Using Variables with Sed in Bash


If you’ve every wanted to do some simple find and replace on string values sed is pretty straightforward way to do it from the command line or a script.

Our starting sed command:

sed 's/findme/replacewithme/g' file-to-search.txt > file-to-write-output.txt

In this command we define a few things:

  • String to find in the supplied file, ex: findme
  • String to replace all instances of the found string with, ex: replacewithme
  • Path to file to search, ex: file-to-search.txt
  • Path to file to output results (optional), ex: file-to-write-output.txt

This works well but it’s hard coded and not very flexible, let’s use a few variable’s to fix that. In order for our variables to be recognized and interpreted we need to use " ", double quotes around our command. And to avoid some (not all) issues with strings possibly being passed in without escaping we can change our delimiter from / to |.


sed "s|$OLD|$NEW|g" file-to-search.txt

Updates to our command and portability have drastically improved with this small change. Note: we haven’t addressed all issues with escaping characters. If you control the variables for input and output, be sure to escape characters and test accordingly.