I have the following code in a LaTeX file:

for \emph{service} in \emph{host}.resources:
    for \emph{file} in \emph{host}.resources:
    for \emph{package} in \emph{host}.resources:

Because this is inside a listing enviroment and I still want the emph and underline commands I escape the LaTeX commands, which results in something like this:

for %*\emph{file}*) in %*\emph{host}*).resources:

I tried to automate this process using the following sed command:

sed "s_\(\\emph{[a-z]*}\)_%\*\1\*)_"

But this results into the following output:

for \%*emph{dir}*) in \emph{host}.resources:

There are two problems with this:

  1. The '\' before emph is placed before the LaTeX escaping characters.
  2. sed only seems to replace the first match. I know about the greedy matching in sed, which is why I used [a-z]* instead of .* inside the curly braces. But this doesn't seem to work.

Any ideas on how to make sed do as I want?

  • You want to replace every occurrence of \emph{anything} with \%*emph{anything}*?
    – mikeserv
    May 25, 2014 at 8:00
  • \emph{X} should become %*\emph{anything}*).
    – HDW
    May 25, 2014 at 11:58

1 Answer 1


Found it.

Because of the double quotes used in the sed command, I should escape my slashes for both sed and bash. Changing in single quotes makes it so that bash ignores the escapes so that's the first problem solved.

By adding 'g' at the end of the sed command (global replace) it now matches everything on the line.

End result:

sed 's_\(\\emph{[a-z]*}\)_%\*\1\*)_g' 
  • 1
    You shouldn't use the reference at all. s|\\emph{[^}]*}|%*&*|g is what you should do.
    – mikeserv
    May 25, 2014 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.