0

I have a big SQL file with content like

[code language="bash"]
git checkout master
git pull origin master
...
[/code]
Lorem ipsum dolor sit amet, consectetur adipiscing elitUt enim ad minim 
[code]some other code[/code]
veniam, quis nostrud exercitation
[code language="php"]var_dump($data);[/code]

And I want to replace the [code language="{lang}"]{wrapped-code}[/code] by <pre><code class="language-{lang}">{wrapped-code}</code></pre>

So the final output will look like

<pre><code class="language-bash">
git checkout master
git pull origin master
...
</code></pre>
Lorem ipsum dolor sit amet, consectetur adipiscing elitUt enim ad minim 
<pre><code>some other code</code></pre>
veniam, quis nostrud exercitation
<pre><code class="language-php">var_dump($data);</code></pre>

Please let me know how we can achieve this with sed or other find and replace command.

0

1 Answer 1

2
sed -e 's/\[code language="\([^"]*\)"\]/<pre><code class="language-\1">/' \
    -e 's!\[/code\]!</code></pre>!' \
    < input  > output

The square brackets have to be escaped so that they don't represent a set of characters; I then capture the text between the quotes to use in the replacement (as \1); for the second search & replacement, I used ! as the separator to avoid Leaning Toothpick Syndrome with the HTML end-tag replacements.

5
  • That works brilliantly. I forgot to mention that I have simple block as well [code]some other code[/code] which needs to be converted as <pre><code>some other code</code></pre>
    – MagePsycho
    Commented Aug 25, 2018 at 11:04
  • And why -e is used instead of -E?
    – MagePsycho
    Commented Aug 25, 2018 at 11:19
  • 1
    Glad to hear it works for you; if you edit your question to include the [code] transformation, I'll update the Answer to cover that case as well. I used -e because I think it's clearer than using semicolons to separate multiple statements. The -E flag is different; it turns on extended regular expressions.
    – Jeff Schaller
    Commented Aug 25, 2018 at 11:46
  • waiting for your updated answer.
    – MagePsycho
    Commented Aug 25, 2018 at 16:57
  • The question doesn’t yet talk about the transformation in your comment above; would you please add it? Thank you.
    – Jeff Schaller
    Commented Aug 25, 2018 at 16:59

You must log in to answer this question.

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