---
title: Using Variables with Sed in Bash
description: If you need to use sed to handle some find and replace functionality of text, here are some ways to make your commands more maintainable over time.
date: 2020-01-12
tags: Sed, Bash
source: https://brianchildress.co/blog/using-variables-with-sed
---

# 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:

```sh
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 `|`.

```sh
OLD=find-this-string
NEW=replace-with-this-string

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.
