Description
Given a LaTeX file with several mathematical formulas inside where each of them is preceded and followed by tag lines \[ and \], respectively. For example, we want to change the block
\[
y = x + 2
\]
to
\begin{equation}
\label{eqn:x}
y = x + 2
\end{equation}
where x is the formula number numbered from the head of the file.
Raw Input Desired Output
some texts
\[
 y = x + 2
\]
some texts
\[
 z = x^3 + 3*x^2 - 1
\]
some texts
\[
 w = x^4 - 4*y^3
\]
some texts
\[
 z = x^2 - y
\]
some texts
\begin{equation}
\label{eqn:1}
 y = x + 2
\end{equation}
some texts
\begin{equation}
\label{eqn:2}
 z = x^3 + 3*x^2 - 1
\end{equation}
some texts
\begin{equation}
\label{eqn:3}
 w = x^4 - 4*y^3
\end{equation}
some texts
\begin{equation}
\label{eqn:4}
 z = x^2 - y
\end{equation}
Script and Comments
Script1
[ 1] /^\\[][]$/!b
[ 2] s/\\\]/\\end{equation}/
[ 3] t
[ 4] g
[ 5] s/[0-9]9*$/\n&/
[ 6] h
[ 7] y/0123456789/1234567890/
[ 8] G
[ 9] s/^.*\n(.*)\n(.*)\n.*/\2\1/
[10] s/^(0*)\n*$/1\1/
[11] h
[12] s/^.*/\\begin{equation}\n\\label{eqn:&}/
Comments
  1. The `-r' option of GNU sed must be used or you have to escape the parentheses used in Steps [9] and [10].
  2. This script use the Hold Space as a counter to keep the number of the current formula. The initial value of that counter is null(empty string).
  3. Every time a line of the form \[ is reached, the counter will be increased by one.
  4. Step [1] makes sed print a line and then start a new cycle if the line is neither \[ nor \].
  5. Steps [2] and [3] change the \] tag line and then makes sed start a new cycle.
  6. Steps [4] thru [11] do the arithmetic job:
    • Step [4] copies the value of the counter from the Hold Space to the Pattern Space.
    • Step [5] inserts a newline character before the digits consisting of a non-9 digit (which may not exist) then followed by 9s. These digits will be changed in the increase by one.
    • If the value of the counter is 12999, Steps [4] thru [11] will increase it to 13000:
      After StepPattern SpaceHold Space
          12999
      4 12999 12999
      5 1\n2999 12999
      6 1\n2999 1\n2999
      7 2\n3000 1\n2999
      8 2\n3000\n1\n2999 1\n2999
      9 13000 1\n2999
      10 13000 1\n2999
      11 13000 13000
    • Step [10] will prepend a `1' to the counter if its value is
      • a sequence of 0s. For example, `0000' which is resulting from adding 1 to `9999', or
      • null, which is the initial value of counter.