# Insert multiline text into several files via commandline

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

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{ngerman}


What's the best way to do this automatically?

-
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

One way using GNU sed:

Content of script.sed:

/^\\documentclass[^{]*{[^}]*}/ {
a\
\\usepackage[utf8]{inputenc}\
\\usepackage[T1]{fontenc}\
\\usepackage{ngerman}
}


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.

-
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

#!/bin/sh
sed '
/\\begin{document}/ a\
\\usepackage[utf8]{inputenc}\
\\usepackage[T1]{fontenc}\
\\usepackage{ngerman}
' \$1
`

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

-