This post was first published on my blog @ https://singhkays.com/blog/sed-error-i-expects-followed-by-text/
If you’d like to subscribe for more updates use the RSS feed or follow me on Twitter @singhkays
I ran into a very weird error today. While trying to automate the deployment for this blog, I needed to replace a string in a file. The internet tutorials [1, 2, 3, 4] told me that sed
would be perfect for this job and the following command should work:
sed -i 's/search_string/replace_string/' filename
The Error
However, I kept getting tripped up by the following error:
sed: 1: "i2.html": command i expects \ followed by text
I spent a bunch of time trying to make sure I escaped the right characters in my strings but the error was persistent! What a nuisance! 😭
The Issue
Upon further searching, the issue turns out to be differences in sed on Mac systems vs Linux. As is with every question asked, StackOverflow has an answer. High Performance Mark explains:
Your Mac does indeed run a BASH shell, but this is more a question of which implementation of sed you are dealing with. On a Mac sed comes from BSD and is subtly different from the sed you might find on a typical Linux box. I suggest you
man sed
.
The Fix
It turns out that providing the backup extension is required when using the -i
switch. chipiik provides the answer that works!
This works with both GNU and BSD versions of sed:
sed -i'' -e 's/old_link/new_link/g' *
or with backup:
sed -i'.bak' -e 's/old_link/new_link/g' *
Note missing space after
-i
option! (Necessary for GNU sed)
Conclusion
HowToGeek described it perfectly:
The
sed
command is a bit like chess: it takes an hour to learn the basics and a lifetime to master them (or, at least a lot of practice).
Happy editing!