2

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

etc.

How can I do this?

2 Answers 2

3

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
5
  • looks nice, just one \ missed (perhaps through autoformatting): sed -r 's/*([^*]+)*/{\\\i \1}/g' file
    – Inno
    Jan 25, 2013 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, 2013 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, 2013 at 14:47
  • Note that the syntax is GNU specific, so would have to be adapted when ported to a non-GNU system. Jan 25, 2013 at 14:48
  • It's running on windows. Thank you very much.
    – Inno
    Jan 25, 2013 at 14:48
2

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)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .