2

Data

7. Masi is the same as
\begin{enumerate}
A
B
ABC ha lorem
\end{enumerate}

1. ABC is
\begin{enumerate}
P
B
Lorem maam
\end{enumerate}

which I want to be

7. Masi is the same as
\begin{enumerate}
\item A
\item B
\item ABC ha lorem
\end{enumerate}

1. ABC is
\begin{enumerate}
\item P
\item B
\item Lorem maam
\end{enumerate}

My startup regex is based on this answer

perl -000pe
s/\n/\n\\begin{enumerate}\n [A-Za-z1-9]* \end{enumerate}/
... [problem here!]
masi.tex

where

  • -000 : activate Perl's paragraph mode, this causes "lines" to be defined by two consecutive newlines (\n\n), so that each of your questions is treated as a single line.
  • -pe : read each line of the input file and print it (-p) after applying the script passed as -e.

I want to replace the beginning of each new line inside the match with \item. My pseudocode for problem here code

s/\n/\item /g

to apply things inside enumerate environment.

How

  • 1
    Please remember to accept an answer on your previous question. Accepting your own is fine and there is no reason to make it community wiki. – terdon Jun 5 '14 at 12:24
4

You could ue the .. or range operator to confine substitutions to the begin/end sections:

while (<DATA>) {
   if ( /\\begin/ .. /\\end/ ) {
       s/^(?!\\)/\\item /;  
   }
   print;
}

__DATA__
7. Masi is the same as
\begin{enumerate}
A
B
ABC ha lorem
\end{enumerate}

1. ABC is
\begin{enumerate}
P
B
Lorem maam
\end{enumerat

If you prefer a command-line script:

perl -ne 'if (/\\begin/../\\end/) {s/^(?!\\)/\\item /};print'

Or, shorter with an implicit print:

perl -pe 'if (/\\begin/../\\end/) {s/^(?!\\)/\\item /}'

The (?!...) is a negative look-ahead assertion.

  • your first perl command fails to add \item before A,B,P. – Avinash Raj Jun 5 '14 at 13:32
3

Another Perl solution:

$ perl -pe '
    if (/\\begin/../\\end/) {
        next if /\\begin/ || /\\end/;
        s/^/\\item /;
    }
' file
7. Masi is the same as
\begin{enumerate}
\item A
\item B
\item ABC ha lorem
\end{enumerate}

1. ABC is
\begin{enumerate}
\item P
\item B
\item Lorem maam
\end{enumerate}

Explanation

  • if (/\\begin/../\\end/): our lines delimiter start with \begin and end with \end.
  • next if /\\begin/ || /\\end/: we don't need start and end, skip them.
  • s/^/\\item /: we replace start of each lines with our desired pattern.
  • -p option causes perl print each lines after we processed it.
2

Use a flag. Set it to 1 when entering enumerate, clear it on the end. Insert item when the flag is set:

perl -pe '$inside = 0 if /\\end{enumerate}/;
          print "\\item " if $inside;
          $inside = 1 if /\\begin{enumerate}/;
         ' input.tex

Note that I check the end before printing so the \item is not prepended to the end line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.