Replace apostrophes with sed

How to replace straight and curly apostrophes with sed: shell quoting, UTF-8 pitfalls, what the change does to your text, and when plain ASCII is the safer choice.

Replacing apostrophes with sed is usually one of four jobs. You might be converting typographic (curly) apostrophes back to the plain ASCII character. You might be turning plain apostrophes into curly ones. You might be escaping apostrophes for SQL or HTML, or deleting them. sed handles all four, but two things trip people up: the shell quoting around the sed script, and the fact that there is more than one apostrophe-like character. This review covers both, explains what the substitution changes in your text, and describes when the result stays usable after copying or sharing.

Is a sed apostrophe replacement suitable for your use?

Converting curly apostrophes to straight ones is safe and predictable. Every right single quotation mark becomes the ASCII apostrophe, and the text keeps its meaning. The decisive tradeoff is typographic: you lose the distinction between an apostrophe, an opening single quote and a closing single quote. Choose this direction for anything machine-read, such as source code, shell scripts, JSON, CSV, configuration files and command-line arguments. In those formats a curly quote is a different character, not a stylistic variant, and it can break parsing.

Converting straight apostrophes to curly ones is riskier. A single ASCII character stands in for several typographic roles, so a blanket replacement puts the wrong mark at the start of quoted phrases. It also corrupts any embedded code or measurements. Treat this direction as suitable only for prose you can review afterward. It is not suitable for files that mix prose with code.

Plain text is preferable whenever the output will be pasted into a terminal, a spreadsheet formula, a programming language or a search box whose matching behavior you have not checked. It is also preferable when you cannot rule out an encoding mismatch somewhere downstream.

What the substitution changes

sed changes the stored characters in the text stream. This is different from presentation-level effects. A font may draw the ASCII apostrophe with a slight curve, and a CSS rule can change how quotation marks look, but neither changes the underlying character. A word processor's smart-quotes feature changes characters as you type. sed does the same kind of change, but in bulk and without any sense of context. After a sed substitution, the file contains different code points. Anything that reads the file will see the new characters, whatever font it uses.

The word apostrophe covers several distinct Unicode characters. A replacement only affects the exact characters your pattern names, so it helps to know which ones appear in your input:

Character | Code point and name | Typical role
' | U+0027 APOSTROPHE | Plain ASCII apostrophe; used in code, shells and data files
’ | U+2019 RIGHT SINGLE QUOTATION MARK | Typographic apostrophe and closing single quote
‘ | U+2018 LEFT SINGLE QUOTATION MARK | Opening single quote; often wrongly inserted by auto-correction before abbreviated years
ʼ | U+02BC MODIFIER LETTER APOSTROPHE | Letter-like apostrophe used in some orthographies
′ | U+2032 PRIME | Feet, minutes and similar units; not an apostrophe
` and ´ | U+0060 GRAVE ACCENT, U+00B4 ACUTE ACCENT | Sometimes typed as substitutes for an apostrophe

Be careful about folding primes into apostrophes. In text such as 5′10″ the prime is a unit symbol, so converting it to an apostrophe is a small change in meaning, not a typographic cleanup.

Getting the shell quoting right

sed scripts are usually wrapped in single quotes, and a single-quoted shell string cannot contain a single quote. The usual workarounds are shown below. Each one replaces the ASCII apostrophe with a curly one:

sed "s/'/’/g" file.txt          # double-quoted script
sed 's/'\''/’/g' file.txt       # close quote, escaped quote, reopen
sed $'s/\'/’/g' file.txt        # bash/zsh ANSI-C quoting
sed 's/\x27/’/g' file.txt       # GNU sed hex escape for U+0027

Double quotes are the simplest option. Inside double quotes, though, the shell still expands dollar signs, backticks and some backslashes, so scripts containing those characters need extra escaping. The hex escape is a GNU sed extension, not POSIX, so do not rely on it with the BSD sed shipped on macOS. If a script grows complicated, put it in a file and run it with sed -f; quoting then stops being a problem.

Common replacements

Normalize curly and modifier apostrophes to plain ASCII. Using separate expressions avoids depending on how the current locale handles multibyte characters:

sed -e "s/’/'/g" -e "s/‘/'/g" -e "s/ʼ/'/g" file.txt

echo "It’s Sam’s" | sed "s/’/'/g"
# It's Sam's

Convert plain apostrophes to curly ones. The blanket version is correct for contractions and possessives, but wrong for opening quotes:

echo "don't stop" | sed "s/'/’/g"
# don’t stop

echo "'Hello,' she said" | sed "s/'/’/g"
# ’Hello,’ she said     <- the opening mark is wrong

A common heuristic treats an apostrophe at the start of a line, or after a space, opening parenthesis or double quote, as an opening quote. Every other apostrophe becomes a right single quotation mark. It fixes the example above but still mislabels elisions such as ’90s and rock ’n’ roll, which take the right single quotation mark even at the start of a word:

sed -E "s/(^|[[:space:](\"])'/\1‘/g; s/'/’/g" file.txt

echo "'Hello,' she said" | sed -E "s/(^|[[:space:](\"])'/\1‘/g; s/'/’/g"
# ‘Hello,’ she said

echo "the '90s" | sed -E "s/(^|[[:space:](\"])'/\1‘/g; s/'/’/g"
# the ‘90s     <- should be ’90s

Escape or remove apostrophes. In a sed replacement, an ampersand stands for the matched text, so an HTML entity needs the ampersand escaped. Doubling apostrophes for SQL string literals works mechanically. When you control the code, parameterized queries are the sounder fix, because they do not depend on escaping:

echo "O'Brien" | sed "s/'/''/g"
# O''Brien

echo "it's" | sed "s/'/\&#39;/g"
# it&#39;s

echo "it's" | sed "s/'//g"
# its

Encoding and locale pitfalls

In UTF-8 the curly apostrophe is three bytes: E2 80 99. A literal substitution of that whole sequence works in any locale, because sed matches the same bytes either way. Bracket expressions are different. A pattern such as [‘’] is safe only when sed runs under a UTF-8 locale. In the C or POSIX locale, sed may treat each byte as a separate character, matching fragments of other characters and leaving broken bytes behind. The separate -e expressions shown earlier sidestep this.

If a file is not UTF-8 in the first place, for example a legacy Windows-1252 export, the curly apostrophe is a single different byte. A UTF-8 pattern will not match it. Check the encoding before assuming the substitution did nothing because no apostrophes were present.

Editing files in place and verifying the result

Both GNU and BSD sed accept a backup suffix attached to -i. Without a backup the forms differ: GNU sed takes plain -i, while BSD sed needs an explicit empty argument, -i ''. Keeping a backup is worthwhile, because a substitution applied to the wrong character class is tedious to undo by hand.

sed -i.bak "s/’/'/g" notes.txt

grep -c "’" notes.txt                # remaining curly apostrophes (line count)
printf '%s' "’" | od -An -tx1        # confirm the bytes you are matching
#  e2 80 99

Comparing the backup with the edited file using diff before deleting the backup is the most direct way to confirm that only apostrophes changed.

Will the result stay readable after copying or sharing?

Straight apostrophes are ASCII. They survive copying, pasting and transfer between systems without encoding problems. Curly apostrophes survive as long as every step treats the text as UTF-8. When one step does not, the usual symptom is mojibake: a UTF-8 right single quotation mark read as Windows-1252 shows up as ’. Use plain text whenever the destination's encoding handling is unknown.

Search and editing are affected too. The straight and curly forms are different characters. Whether a search for don't finds don’t depends on whether the search tool normalizes punctuation, and many command-line tools such as grep do not. Mixed apostrophes in one document can therefore cause missed matches, failed find-and-replace runs and duplicate-looking entries in sorted lists. Normalizing to one form, whichever you choose, avoids most of this.

Reading order is not affected. Replacing one apostrophe character with another does not reverse, mirror or reorder text, and it does not change bidirectional display.

For assistive technology, no documentation or test results were supplied for this review. It makes no claim about how particular screen readers announce straight, curly or modifier apostrophes. If that matters for your audience, test with the specific screen reader and settings your readers use.

Gaps in this review

  • Behavior in specific destinations such as particular email clients, content management systems, spreadsheets or messaging apps was not tested and is not documented here.
  • Screen reader handling of the different apostrophe characters is not covered by supplied evidence.
  • Support for hex escapes and multibyte bracket expressions in non-GNU sed implementations should be confirmed against your system's own manual page before you rely on them.