Reputation: 4950
I'm trying here to convert old fashion phpBB
code blocks to MARKDOWN
using sed
.
Please consider following data sample:
cat sed.txt
[code]xxxx-YYY-xxxx[/code]
Some text
[code]yyyy-ZZZ-yyyy[/code]
More text
Bogus code block[/code]
[code]zzzz-XXX-zzzz[/code]
After long trial and error I've ended up with the following strategy:
sed -ne '
/\[code\].*\[\/code\]/ {
s#\[/*code\]##g
s#^#\n\n #
s#$#\n\n#p
}' sed.txt | cat -Av
$
$
xxxx-YYY-xxxx$
$
$
$
$
yyyy-ZZZ-yyyy$
$
$
$
$
zzzz-XXX-zzzz$
$
$
This works great, however I find it would be easier and seem more natural to do it this way:
sed -ne '
/\[code\].*\[\/code\]/ {
s#\[/*code\]#\n\n#g
s#^# #p
}' sed.txt | cat -Av
$
$
xxxx-YYY-xxxx$
$
$
$
$
yyyy-ZZZ-yyyy$
$
$
$
$
zzzz-XXX-zzzz$
$
$
But that does not work as expected. Any suggestions why, how to get around this?
Thank you
Upvotes: 0
Views: 445
Reputation: 58381
This might work for you (GNU sed):
sed -nr 's/^\[(code\])(.*)\[\/\1$/\n\n \2\n\n/p' file | sed -n l
N.B. In your script you prepend 2 newlines to the beginning of the pattern space and then prepend 4 spaces again, thus the indentation is added infront of the first of the newlines not infront of the text.
Upvotes: 0
Reputation: 10039
sed '/\[code\].*\[\/code\]/ {
s#\[code]#& #g
s#\[/*code\]#\
\
#g
}' sed.txt
order of substitution is important and changed between your two sample
I also change a bit the behavior, the -n
and p
are not needed in this text sample (but maybe if coming from a biggest structure)
(test on my aix so posix version)
Upvotes: 2