Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

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

2 Answers 2

up vote 4 down vote accepted

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.

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

#!/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)

share|improve this answer

Your Answer

 
discard

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.