How to Escape Single Quotes in sed (With Example)


Often you may want to escape single quotes when writing code with sed.

The easiest way to do so is by simply writing the sed code in double quotes.

Here is an example:

sed "s/Zachs/Zach's/" some_strings.txt

This particular example will replace each occurrence of Zachs with Zach’s in the file named some_strings.txt.

By placing double quotes around the sed code, we are able to escape the single quote.

Note that we use the s command in sed in to “substitute” one pattern for another pattern.

The following example shows how to use this syntax in practice.

Example: How to Escape Double Quotes in sed

Suppose that we have a file named some_strings.txt.

We can use the cat command to view the contents of this file:

Suppose that we would like to replace each occurrence of Zachs with Zach’s in the file.

We can use the following syntax with sed to do so:

sed "s/Zachs/Zach's/" some_strings.txt 

The following screenshot shows how to use this syntax in practice:

sed escape single quote

Notice that each occurrence of Zachs has been replaced with Zach’s in the file.

By wrapping the sed code in double quotes, we were able to escape the single quote when specifying the replacement pattern to use.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Replace newline with space
How to Use sed to Replace newline with comma
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply