Minustar
Minustar

Reputation: 1225

Check of file contains a line beginning with 'xxx' but not 'yxxx'

I am writing a small bash script that checks whether to execute makeindex or not if a .tex file contains the line \makeindex. The MakeIndex run would not be run if the command is commented-out.

How do I check that a file, say source.tex has the line?

I know that I need grep—I am, however, fairly new to regexes and bash scripting.

Upvotes: 1

Views: 1452

Answers (3)

Kevin
Kevin

Reputation: 56149

It seems your title and question are asking different things. As a couple people have already answered your title, I'll address your question.

As I recall, tex comments are %. So we'll search for a line that contains \makeindex without a % before it on the line:

grep '^[^%]*\\makeindex' source.tex
#grep -- the program we're running, obviously.
#    '                 ' -- Single quotes to keep bash from interpreting special chars.
#     ^ -- match the beginning of a line
#      [  ] -- match characters in the braces.
#       ^  -- make that characters not in the braces.
#        % -- percent symbol, the character (in the braces) we do not want to match.
#          * -- match zero or more of the previous item (non-percent-symbols)
#           \\ -- a backslash; a single one is used to escape strings like '\n'.
#             makeindex -- the literal string "makeindex"
#                        source.tex-- Input file

Sample:

$ grep '\\end' file.tex
51:src/file.h\end{DoxyCompactItemize}
52:%src/file.h\end{DoxyCompactItemize}
53:src/%file.h\end{DoxyCompactItemize}
54:    %\end{DoxyCompactItemize}
55:src/file.h\end{DoxyCompactItemize}%
$ grep '^[^%]*\\end' file.tex
51:src/file.h\end{DoxyCompactItemize}
55:src/file.h\end{DoxyCompactItemize}%
$

Upvotes: 2

SiegeX
SiegeX

Reputation: 140557

You can do this with one call to awk:

#!/bin/bash
if awk '/^xxx/{f=1}/^yyy/{f=0}END{if(!f)exit 1}' file; then
  echo "file OK"
else
  echo "file BAD"
fi

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143329

If you want to anchor match to the beginning of line it's

grep ^xxx files...

Upvotes: 2

Related Questions