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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityAssuming that each occurrence of *some text*
is on a single line (ie. not split across multiple lines):
sed -r 's/\*([^*]+)\*/{\\i \1}/g' file
sed
you use. I get the same output with \\\i
as with \\i
. I am using `GNU sed version 4.2.1'
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)