1

I currently have a set of default LaTeX packages I use frequently formatted as follows:

package1
[options]package2
[options]package3
package4
...

I would like to be able to convert this to standard LaTeX notation of \usepackage[options]{package} or \usepackage{package} depending on whether the package has additional options. I have successfully created a sed/regex command to convert the lines with options, but it misses the packages without options.

echo "[option]package" | sed 's/.*\(\[[^]]*\]\)\(.*\)/\\usepackage\1{\2}/'
>> \usepackage[option]{package}

When this is run on a line with just a package, it fails (as I would expect).

echo "package" | sed 's/.*\(\[[^]]*\]\)\(.*\)/\\usepackage\1{\2}/'
>> package

Is this a regex problem and if so, how should I approach it?

2 Answers 2

2

Please verify if this works for you:

$ echo -e "[options]package3\npackage4" | sed 's/^\(\[[^]]*\]\)\?\(.*\)/\\usepackage\1{\2}/'
\usepackage[options]{package3}
\usepackage{package4}

I replaced .* with ^ to match the start of line and added \? to make the brackets optional.

0

This two-step approach seems to be simpler:

$ printf '%s\n' 'package1' '[options]package2' | sed -e 's/[^]]*$/{&}/' -e 's/^/\\usepackage/'
\usepackage{package1}
\usepackage[options]{package2}
  • The first step, s/[^]]*$/{&}/, puts the project name into curly braces by matching the longest possible string of characters other than ], up to the end of the line.
  • The second step, s/^/\\usepackage/, simply prepends \usepackage to the beginning of the line.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.