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 am trying to configure some external commands in Gedit3, for compiling LaTeX files. All works well, except for the following. I have a LaTeX document, consisting of many parts. Each file begins with

% mainfile: name_of_main_file.tex

So in bash I'm trying to extract the first line of each file, and from that line extract name_of_main_file.tex and compile that. So the question is: what is the quickest way of extracting name_of_main_file.tex, loading it into a variable, say $MAINFILE, so that then I can compile that?

share|improve this question
up vote 4 down vote accepted

for file in *.tex; do
  read _ _ mainfile < "$file"
  echo "$file : $mainfile"

Note: I am assuming the files you want to extract the first lines from are .tex files, if this is not the case then change the *.tex part accordingly

share|improve this answer
Excellent! Works like a charm. Thanks! The loop is actually unnecessary for me, since what I'm really trying to accomplish is this: I have a file opened in gedit, which is not necessarily the master LaTeX file, but its first line tells me what the master file is. I am trying to extract that line and compile the master file. Anyway, thanks for your help, it works! – William Jan 24 '12 at 9:13

This should do the work (untested):

sed -sn 1p *.tex | cut -f2 -d: | xargs latex
share|improve this answer
(+1) especially for the reminder about sed -s... – Peter.O Jan 24 '12 at 10:37
Do you maybe want to add sort -u to cut down on the duplicates passed to xargs? – glenn jackman Jan 24 '12 at 18:13

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.