Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to insert some code into multiple tex files foo*.tex in a directory, one line after \documentclass{.*}. Note that the files have different document classes so the .* is just a symbolic placeholder here.

The code has multiple lines, for example


What's the best way to do this automatically?

share|improve this question
Doesn't TeX have "include"-type directives? – Mat May 1 '12 at 9:22
Yes, but I don't want to use include in this case – student May 1 '12 at 9:24
Sorry, I confused \begin{document} with \documentclass{.*}. I edited the question to fix this. But then it becomes a bit more complicated because there are multiple documentclasses in the files (for example article or beamer) – student May 1 '12 at 10:00
@student: But documentclass also have options with following format: \documentclass[options]{style}. Do you mean without any option? – Birei May 1 '12 at 10:04
It would be sufficient without options in this case. But I guess that one could just use a regular expression which matches \documentclass.* or something like that, the input code should be placed into a new line anyway. – student May 1 '12 at 10:07
up vote 4 down vote accepted

One way using GNU sed:

Content of script.sed:

/^\\documentclass[^{]*{[^}]*}/ {

Run it like:

sed -s -i.bak -f script.sed foo*.tex

I use ^ to match the documentclass at the beginning of the line. Remove it if you can have spaces before it.

The -s switch considers each input as a different file, and -i creates backups with bak extension.

share|improve this answer
I get sed: file script.sed line 4: unknown command: ` – student May 1 '12 at 9:37
@student: Sorry. An error copying the code. Fixed now. – Birei May 1 '12 at 9:42
Thanks. Sorry, I confused \begin{document} with \documentclass{...}. See my edit. Would be nice if you could include this change into your answer. – student May 1 '12 at 10:01
@student: Edited answer. – Birei May 1 '12 at 10:14

the following shell script should do it

sed '
/\\begin{document}/ a\
' $1

simply call the script with your files as input (one by one)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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