Issue
I am converting a custom markup language to TeX.
I have a file like this:
\macro{stuff}
{more stuff}
{yet other stuff}
{some stuff}
these are extra lines
another extra line
there can be any number of extra lines
e
\macro{yet more stuff stuff}
{even more stuff}
{yet other stuff}
{some stuff}
this is extra
this is extra too
e
I need the result to be this:
\macro{stuff}
{more stuff}
{yet other stuff}
{some stuff}{
these are extra lines
another extra line
there can be any number of extra lines
}
\macro{yet more stuff stuff}
{even more stuff}
{yet other stuff}
{some stuff}{
this is extra
this is extra too
}
Notice e
is by itself on a line, indicating the end of a set of data, it simply gets replaced with a closing bracket.
I could simply use this:
sed -i 's/^e$/}/g' file.tex
Resulting in this:
\macro{stuff}
{more stuff}
{yet other stuff}
{some stuff}
these are extra lines
another extra line
there can be any number of extra lines
}
\macro{yet more stuff stuff}
{even more stuff}
{yet other stuff}
{some stuff}
this is extra
this is extra too
}
The problem is, I also need a matching starting bracket to surround this extra text before the e
.
One way to think of it is:
- Replace every occurrence of
}
. - But only if that occurrence is at the end of the line.
- And only if that it is the last occurrence appearing before an
e
appearing completely by itself.
This is the closest I can figure, not sure how to match across any number of lines not containing more matches of }$
:
sed -i 's/}$\n.*\n.*\n.*\n^e$/}{&}/g' file.tex
How can I wrap that final extra text inside {
and }
?
Solution
It is easier to do this using awk
using an empty RS
. Here is a gnu-awk
solution:
awk -v RS= '{sub(/.*}/, "&{"); sub(/\ne$/, "\n}"); ORS=RT} 1' file
\macro{stuff}
{more stuff}
{yet other stuff}
{some stuff}{
these are extra lines
another extra line
there can be any number of extra lines
}
\macro{yet more stuff stuff}
{even more stuff}
{yet other stuff}
{some stuff}{
this is extra
this is extra too
}
Or in any version of awk
:
awk -v RS= '{sub(/.*}/, "&{"); sub(/\ne$/, "\n}\n")} 1' file
Answered By - anubhava Answer Checked By - Marie Seifert (WPSolving Admin)