Shell – Extract part of the first line of a file

shelltext processing

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?

Best Answer

#!/bin/bash

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

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

Related Question