| SGREP(1) | General Commands Manual | SGREP(1) |
sgrep - search a file for a structured pattern
sgrep [-aCcDdhiIlNnPqSsTtV] [-g option] [-O filename] [-o "format"] [-p preprocessor] [-w char list] [-x filename] [-e] expression [filename ...]
sgrep [-aCcDdhiIlNnPqSsTtV] [-g option] [-O filename] [-o "format"] [-p preprocessor] [-w char list] [-x filename] -f filename [-e expression] [filename ...]
sgrep [-aCcDdhiIlNnPqSsTtV] [-g option] [-O filename] [-o "format"] [-p preprocessor] [-w char list] [-x filename] -f filename -F filename [-e expression]
sgrep -h
sgrep (structured grep) is a tool for searching text files and filtering text streams using structural criteria. The data model of sgrep is based on regions, which are non-empty substrings of text. Regions are typically occurrences of constant strings or meaningful text elements, which are recognizable through some delimiting strings. Regions can be arbitrarily long, arbitrarily overlapping, and arbitrarily nested.
sgrep uses patterns called region expressions to express which regions of the input text are output to standard output. The selection of regions is based on mutual containment and ordering conditions of the regions, expressed by the region expression.
Region expressions are read by default first from file $HOME/.sgreprc, or if it doesn't exist, from file /usr/lib/sgreprc, and then from the command line. Different behavior can be specified through command line options.
Input files are processed one by one (i.e., regions cannot extend over file boundaries), except if the -S flag is given, in which case sgrep takes the concatenation of the input files as its input text. If no input files are given, sgrep reads the standard input. Standard input can also be specified as an input file by giving hyphen '-' as a file name.
The selected regions are output in increasing order of their start positions. If several output regions overlap, a minimal region that covers them all is output, by default, instead of outputting each of them separately.
sgrep -S file_1 ... file_n
is similar to
cat file_1 ... file_n | sgrep
except that the latter creates a temporary disk file of the input stream. Sgrep may use much more memory when run with the -S option, since then it cannot release its internal region lists between processing each file.
A list of options can be given also as the value of the environment variable SGREPOPT.
region_expr -> basic_expr
| operator_expr
operator_expr -> region_expr ['not'] 'in' basic_expr
| region_expr ['not'] 'containing' basic_expr
| region_expr ['not'] 'equal' basic_expr
| region_expr 'or' basic_expr
| region_expr 'extracting' basic_expr
| region_expr '..' basic_expr
| region_expr '_.' basic_expr
| region_expr '._' basic_expr
| region_expr '__' basic_expr
| region_expr 'quote' basic_expr
| region_expr '_quote' basic_expr
| region_expr 'quote_' basic_expr
| region_expr '_quote_' basic_expr
| 'concat' '(' region_expr ')'
| 'inner' '(' region_expr ')'
| 'outer' '(' region_expr ')'
| 'join' '(' integer ',' region_expr ')'
basic_expr -> phrase
| 'start'
| 'end'
| 'chars'
| constant_list
| '(' region_expr ')'
phrase -> '"' char [ char ... ] '"'
constant_list -> '[' ']' | '[' regions ']'
regions -> region
| region regions
region -> '(' integer ',' integer ')'
Note that region expressions are left-associative. This means, for example, that an expression
'"<a>".."</a>" or "</b>"'
evaluates to the regions starting with "<a>" and ending with "</a>", or comprising only the string "</b>". In order to obtain the regions that begin with "<a>" and end with either "</a>" or "</b>", one should indicate the proper order of evaluation using parentheses:
"<a>".. ("</a>" or "</b>")
Expressions can also contain comments, which start with '#' and extend to the end of the line. However, a '#'-sign in a phrase does not begin a comment.
The value of an expression is a set of regions of input text that satisfy the expression.
Value v(basic_expr) of a basic expression:
Value v(operator_expr) of operator expressions:
'[(1,4) (3,6) (7,9)] extracting [(2,5) (4,7)]'
consists of the regions (1,1) and (8,9).
Let x and y be two regions. We say that region x precedes region y if the end position of x is smaller than the start position of y. We say that region x is later than region y if the end position of x is greater than the end position of y, or if they end at the same position and the start of x is greater than the start of y. Region x is earlier than region y if the start position of x is smaller than the start position of y, or if they start at the same position and the end position of x is less than the end position of y. Now a region x from v(region_expr) and a region y from v(basic_expr) are paired in expression v(region_expr '..' basic_expr) if and only if
The pairing of regions x and y forms a region that extends from the start position of x to the end position of y.
The below example query finds C-style non-nesting comments:
"/*" quote "*/"
The below example query finds strings between quotation marks:
"\"" quote "\""
(Notice the difference to expression "\"" .. "\"", which would evaluate to any substring of input text that starts with a quotation mark and ends with the next quotation mark.)
The variants _quote, quote_ and _quote_ are analogical to the operators _., ._ and __, in the sense that the "quote regions" originating from the expression on the side of the underscore _ are excluded from the result regions. (In the case of _quote_ any possibly resulting empty regions are excluded from the result.)
'"/*" quote "*/" in join(10,chars)'
selects comments "/* ... */" which are at most 10 characters long.
Count the number of occurrences of string "sort" in file eval.c:
sgrep -c '"sort"' eval.c
Show all blocks delimited by braces in file eval.c:
sgrep '"{" .. "}"' eval.c
Show the outermost blocks that contain "sort" or "nest":
sgrep 'outer("{" .. "}" containing ("sort" or "nest"))'\
eval.c
Show all lines containing "sort" but no "nest" in files with an extension .c, preceded by the name of the file:
sgrep -o "%f:%r" '"\n" _. "\n" containing "sort" \
not containing "nest"' *.c
(Notice that this query would omit the first line, since it has no preceding new-line character '\n', and also the last one, if not terminated by a new-line. For a correct way to express text lines, see the definition of the LINE macro below.)
Show the beginning of conditional statements, consisting of "if" followed by a condition in parentheses, in files *.c. The query has to disregard "if"s appearing within comments "/* ... */" or on compiler control lines beginning with '#':
sgrep '"if" not in ("/*" quote "*/" or ("\n#" .. "\n")) \
.. ("(" .. ")")' *.c
Show the if-statements containing string "access" in their condition part appearing in the main function of the program in source files *.c:
sgrep '"if" not in ("/*" quote "*/" or ("\n#" .. "\n")) \
.. ("(" .. ")") containing "access" \
in ("main(" .. ("{" .. "}")) \
.. ("{" .. "}" or ";")' *.c
We see that complicated conditions can become rather illegible. The use of carefully designed macros can make expressing queries much easier. For example, one could give the below m4 macro processor definitions in a file, say, c.macros:
define(BLOCK,( "{" .. "}" ))
define(COMMENT,( "/*" quote "*/" ))
changecom(%)
define(CTRLINE,( "#" in start or "\n#"
_. ("\n" or end) ))
define(IF_COND,( "if" not in (COMMENT or CTRLINE)
.. ("(" .. ")")))
Then the above query could be written more intuitively as
sgrep -p m4 -f c.macros -e 'IF_COND containing "access"\
in ( "main(" .. BLOCK ) .. (BLOCK or ";")' *.c
sgrep performs common subexpression elimination on the query expression, so that recurring sub-expressions are evaluated only once. For example, in expression
'(" " or "\n" or "\t") .. (" " or "\n" or "\t")'
the sub-expression
'(" " or "\n" or "\t")'
is evaluated only one.
Exit status is 0 if any matching regions are found, 1 if none, 2 for syntax errors or inaccessible files (even if matching regions were found).
One's own default options for sgrep can be given as a value of the environment variable SGREPOPT. For example, executing
setenv SGREPOPT '-p m4 -o %r\n'
makes sgrep to apply m4 preprocessor to the expression and display each output region as such followed by a line feed.
Sgrep tries to read the contents of the files $HOME/.sgreprc and /usr/lib/sgreprc. Generally useful macro definitions may be placed in these files. Using m4 (or some other) macro processor, for example the following definitions could go in one of these files:
define(BLANK,( " " or "\t" or "\n"))
define(LEND,( "\n" or end ))
define(LINE,( start .. LEND or ("\n" _. LEND) ))
define(NUMERAL,( "1" or "2" or "3" or "4" or "5" or
"6" or "7" or "8" or "9" or "0" ))
Jani Jaakkola and Pekka Kilpelainen, University of Helsinki, Department of Computer Science, 1995.
Sgrep may use lots of memory, when evaluating complex queries on big files. When sgrep reads its input text from a pipe, it copies it to a temporary file. sgrep does not have regular expressions in search patters.
awk(1), ed(1), grep(1)
sgrep home page at http://www.cs.helsinki.fi/~jjaakkol/sgrep.html