Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
You want to replace every occurrence of \emph{anything} with \%*emph{anything}*? – mikeserv May 25 '14 at 8:00
\emph{X} should become %*\emph{anything}*). – Foezjie May 25 '14 at 11:58

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' 
share|improve this answer
You shouldn't use the reference at all. s|\\emph{[^}]*}|%*&*|g is what you should do. – mikeserv May 25 '14 at 8:02

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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