Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I would like to replace every occurrence of *text* into {\i text}.

text *text* text
*text* text *text*
*text text text* text

should become

text {\i text} text
{\i text} text {\i text}
{\i text text text} text


How can I do this?

share|improve this question
add comment

2 Answers 2

up vote 3 down vote accepted

Assuming that each occurrence of *some text* is on a single line (ie. not split across multiple lines):

sed -r 's/\*([^*]+)\*/{\\i \1}/g' file
share|improve this answer
looks nice, just one \ missed (perhaps through autoformatting): sed -r 's/*([^*]+)*/{\\\i \1}/g' file –  Inno Jan 25 '13 at 14:44
I did it this way in three steps: sed -e "s/^*/{\\\i /g" -e "s/ */ {\\\i /g" -e "s/*/}/g" file –  Inno Jan 25 '13 at 14:45
It may depend on which sed you use. I get the same output with \\\i as with \\i. I am using `GNU sed version 4.2.1' –  Peter.O Jan 25 '13 at 14:47
Note that the syntax is GNU specific, so would have to be adapted when ported to a non-GNU system. –  Stéphane Chazelas Jan 25 '13 at 14:48
It's running on windows. Thank you very much. –  Inno Jan 25 '13 at 14:48
add comment

With any POSIX sed, and if the *...* may span multiple lines, you could do:

sed -e :1 -e 's/\*\([^*]\{1,\}\)\*/{\\i \1}/g;/\*/!b' -e '$q;N;b1'

Note that some sed implementations have a relatively low limit on the size of their pattern space, so those may fail if the *...* span too many (long) lines.

With perl:

perl -0777 -pe 's/\*(.*?)\*/{\\i $1}/gs'

But beware that it slurps the whole file in memory prior to doing the substitutions which could be a problem for huge files. Also note that perl has a -i option to update the file in place (which some sed implementations have borrowed)

share|improve this answer
add comment

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.