SGREP(1)
hey bestie ๐ welcome to the man page for sgrep โ aka SGREP(1) on the shelf, section 1, general commands. it's structured grep and it's genuinely iconic, let me walk you through it ๐ซถ
๐ธ NAME ๐ธ
sgrepโ search a file for a structured pattern โจ
๐ SYNOPSIS ๐
like, four whole ways to call her, no cap:
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
(yeah there's a -q in there that never got its own little paragraph, don't @ me, that's just how the page is ๐)
๐ฆ DESCRIPTION ๐ฆ
so sgrep (structured grep) is your girl for searching text files and filtering text streams using structural criteria. the whole data model is based on regions, which are non-empty substrings of text. regions are usually occurrences of constant strings or meaningful text elements, and you can spot them because they're recognizable through some delimiting strings. and the best part? regions can be arbitrarily long, arbitrarily overlapping, and arbitrarily nested. literally no rules, main character energy ๐
sgrep uses patterns called region expressions to express which regions of the input text get output to standard output. which regions get picked is decided by mutual containment and ordering conditions of the regions, expressed by the region expression. it's giving "math but make it fashion" ๐
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. you can get different behavior through the command line options, iykyk.
input files are processed one by one (i.e., regions cannot extend over file boundaries), except if the -S flag is given โ in that 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. and if several output regions overlap? a minimal region that covers them all is output, by default, instead of outputting each of them separately. one region to rule them all, periodt โจ
๐ OPTIONS ๐
-aโ act as a filter: display the matching regions, possibly formatted according to the output format, interleaved with the rest of the text. (peep the description of option-obelow ๐)-Cโ display copyright notice.-cโ display only the count of the regions that match the expression. just the number bestie, nothing else ๐ข-Dโ display verbose progress output. > NOTE: this is used for debugging purposes only and may not function in future versions ofsgrep. so pls don't build your whole life on it ๐ญ-dโ display each matching region once, even if the regions overlap or nest.-eexpression โ search the input text for occurrences of expression.-ffile โ read the region expression from the named file. filename-refers to stdin.-Ffilename โ read list of input files from filename instead of command line.-goption โ set scanner option. option can be any of:sgmlโ use SGML scannerhtmlโ use HTML scanner (currently same as SGML scanner)xmlโ use XML scannersgml-debugโ show recognized SGML tokensinclude-entitiesโ automatically include system entities
-hโ display a short help. hi hello, that's her waving at you ๐-iโ ignore case distinctions in phrases.-Iโ switches to indexing mode, when given as first option. (emphasis on first option, she's picky like that ๐)-lโ long output format: precede each output region by a line which indicates the ordinal number of the region, the name of the file where the region starts, the length of the region in bytes, the start and end positions of the region within the entire input text, the start position of the region within the file containing the start, and the end position of the region within the file containing the end. yeah that's a lot of lore ๐-Nโ do not add a newline after the last output region.-nโ suppress reading$HOME/.sgreprcor/usr/lib/sgreprc.-Ofile โ read the output format from file. see the description of output formats below.-oformat โ set the output format. the format is displayed for each output region with any occurrences of the following place holders substituted:%fโ name of the file containing the start of the region%sโ start position of the region%eโ end position of the region%lโ length of the region in bytes (i.e.,%e-%s+1)%iโ start position of the region in the file where the region begins%jโ end position of the region in the file where the region ends%rโ text of the region."%r"is the default output format.%nโ gets the ordinal number of the region
-Pโ display the (preprocessed) region expression without executing it. preview mode, we love a sneak peek ๐ซถ-ppreprocessor โ apply preprocessor to the region expression before evaluating it.-Sโ stream mode. with this optionsgrepconsiders it's input files as a continuous stream, so that regions may extend across file boundaries.
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. heads up bestie: 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 ๐ญ
-sโ short output format (default): do not format the text of the output regions, and display overlapping parts of regions only once.-Tโ display statistics about the execution.-tโ display time usage.-Vโ display version information.-vโ verbose mode. shows what is going on. ๐-wchar list โ set the list of characters used to recognize words.-xfilename โ use given index file instead of scanner. implies-S.--โ no more options. we're done here, that's the end of the options, periodt ๐
a list of options can be given also as the value of the environment variable SGREPOPT.
๐ SYNTAX OF EXPRESSIONS ๐
here's the whole grammar, verbatim, because she's precise and that's her vibe:
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>". but if you want the regions that begin with "<a>" and end with either "</a>" or "</b>", you gotta indicate the proper order of evaluation using parentheses:
"<a>".. ("</a>" or "</b>")
see? parentheses are the moment ๐
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. don't get got by that one ๐
okay that's part 1 bestie, stay tuned, there's more ๐
๐ง SEMANTICS OF EXPRESSIONS โจ
okay so the value of an expression is just a set of regions of input text that satisfy that expression. that's it. that's the whole vibe. ๐
๐ซ Value v(basic_expr) of a basic expression
v(phrase):=
the set of regions of input text whose text equals the text of the phrase. yes bestie, exactly what it sounds like. ๐
v('start'):=
a set consisting of single-character regions for the first position of each input file. But if the -S option is given, the value is a set containing a single region that comprises the first character in the input stream. one file, many files, whole stream โ different beasts, iykyk. โจ
v('end'):=
a set consisting of single-character regions for the last position of each input file. If the -S option is given, the value is a set containing a single region that comprises the last character in the input stream. ๐ฆ
v('chars'):=
a set consisting of all single-character regions. every single one. no skips. ๐
v([ ]):=
an empty set. that's it. nothing. the void. ๐
v([(s_1,e_1) (s_1,e_2) ... (s_n,e_n)]):=
a set consisting of regions r_i for each i = 1,...,n, where the start position of region r_i is s_i and its end position is e_i. Here's the fine print, don't skip it:
- The positions have to be nonnegative integers, and
- the regions have to be given in increasing order of their start positions; regions with a common start positions have to be given in increasing order of their end positions.
- The positions are counted from the first character of each input file, unless the
-Soption is given, in which case the positions are counted starting from the beginning of the input stream. - The number of the first position in a file or a stream is zero.
periodt. ๐
v('('region_expr')'):= v(region_expr).
parentheses just pass the value straight through, no drama. ๐ธ
๐ Value v(operator_expr) of operator expressions
v(region_expr 'in' basic_expr):=
the set of the regions in v(region_expr) that are contained in some region in v(basic_expr).
And now the definition of "contained", because it's specific: a region x is contained in another region y if and only if the start position of x is greater than the start position of y and the end position of x is not greater than the end position of y, or the end position of x is smaller than the end position of y and the start position of x is not smaller than the start position of y.
read that twice bestie, it's a whole logic puzzle and it lowkey eats ๐
v(region_expr 'not' 'in' basic_expr):=
the set of the regions in v(region_expr) that are not contained in any region in v(basic_expr). the inverse energy, we love to see it. ๐
v(region_expr 'containing' basic_expr):=
the set of the regions in v(region_expr) that contain some region in v(basic_expr). โจ
v(region_expr 'not' 'containing' basic_expr):=
the set of the regions in v(region_expr) that do not contain any region in v(basic_expr). ๐ฆ
v(region_expr 'equal' basic_expr):=
The set of regions, which occur in both v(region_expr) and v(basic_expr). the overlap, the mutuals, the shared faves. ๐
v(region_expr 'not equal' basic_expr):=
The set of regions, which occur in v(region_expr) but do not occur in v(basic_expr). ๐
v(region_expr 'or' basic_expr):=
the set of the regions that appear in v(region_expr) or in v(basic_expr) or in both. union energy, everyone's invited ๐ซถ
v(region_expr 'extracting' basic_expr):=
the set of the non-empty regions that are formed of the regions in v(region_expr) by extracting an overlap with any region in v(basic_expr).
fr fr, check the example: the value of
'[(1,4) (3,6) (7,9)] extracting [(2,5) (4,7)]'
consists of the regions (1,1) and (8,9). slay. โจ
v(region_expr '..' basic_expr):
The value of this expression consists of the regions that can be formed by pairing regions from v(region_expr) with regions from v(basic_expr). The pairing is defined as a generalization of the way how nested parentheses are paired together "from inside out". For this we need to be able to compare the order of regions, which may be overlapping and nested. This ordering is defined as follows.
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
- x precedes y,
- x is not paired with any region from
v(basic_expr)which is earlier than y, and - y is not paired with any region from
v(region_expr)which is later than x.
The pairing of regions x and y forms a region that extends from the start position of x to the end position of y. iconic tbh ๐
v(region_expr '._' basic_expr):
The pairing of the regions from v(region_expr) and the regions from v(basic_expr) is defined similarly to v(region_expr '..' basic_expr) above, except that the pairing of regions x and y now forms a region which extends from the start position of x to the position immediately preceding the start of y. ๐ธ
v(region_expr '_.' basic_expr):=
The pairing of the regions from v(region_expr) and the regions from v(basic_expr) is defined similarly to v(region_expr '..' basic_expr) above, except that the pairing of regions x and y now forms a region which extends from the position immediately following the end position of x to the end position of y. ๐
v(region_expr '__' basic_expr):=
The pairing of the regions from v(region_expr) and the regions from v(basic_expr) is defined similarly to v(region_expr '..' basic_expr) above, except that now the pairing of regions x and y forms a region which extends from the text position immediately following the end of x to the text position immediately preceding the start of y. Possibly resulting empty regions are excluded from the result. ๐ฆ
v(region_expr 'quote' basic_expr):
The value of this expression consists of the regions that extend from the start position of a "left-quote region" in v(region_expr) to the end position of a corresponding "right-quote region" in v(basic_expr). The regions in the result are non-nesting and non-overlapping. The left-quote regions and the right-quote regions are defined as follows:
- The earliest region (see above) in
v(region_expr)is a possible left-quote region. - For each possible left-quote region x, the earliest region in
v(basic_expr)preceded by x is its right-quote region. - For each right-quote region y in
v(basic_expr), the earliest region inv(region_expr)preceded by y is a possible left-quote region.
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.) ๐
v('concat' '(' region_expr ')' ):
the set of the longest regions of input text that are covered by the regions in v(region_expr). โจ
v('inner' '(' region_expr ')' ):
the set of regions in v(region_expr) that do not contain any other region in v(region_expr). Note that for any region expression A, the expression inner(A) is equivalent to (A not containing A). ๐
v('outer' '(' region_expr ')' ):
the set of regions in v(region_expr) that are not contained in any other region in v(region_expr). Note that for any region expression A, the expression outer(A) is equivalent to (A not in A). ๐
v('join' '(' n ',' region_expr ')' ):
The value of this expression is formed by processing the regions of v(region_expr) in increasing order of their start positions (and in increasing order of end positions for regions with a common start). Each region r produces a result region beginning at the start of r and extending to the end of the (n-1)th region after r.
heads up bestie: this operation is useful only with non-nesting regions. Especially, when applied to 'chars', it can be used to express nearness conditions.
For example,
'"/*" quote "*/" in join(10,chars)'
selects comments "/* ... */" which are at most 10 characters long. ๐
๐ EXAMPLES OF REGION EXPRESSIONS ๐
okay bestie, this is the part where it all comes together. real queries, real files, real slay. let's go ๐ฆ
Count how many times the string "sort" shows up in eval.c:
sgrep -c '"sort"' eval.c
Show every single block that's delimited by braces in 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 not "nest", only in files with a .c extension, with the name of the file printed before each one:
sgrep -o "%f:%r" '"\n" _. "\n" containing "sort" \
not containing "nest"' *.c
๐จ okay so real talk: this query would skip the very first line, because there's no new-line character'\n'before it, and it would also skip the last line if that line isn't terminated by a new-line. if you want the correct way to express text lines, peep the definition of theLINEmacro further down. iykyk ๐
Show the beginning of conditional statements โ that's "if" followed by a condition in parentheses โ in files *.c. But this query has to disregard any "if" that shows up inside comments /* ... */ or on compiler control lines that start with '#':
sgrep '"if" not in ("/*" quote "*/" or ("\n#" .. "\n")) \
.. ("(" .. ")")' *.c
Show the if-statements that have the string "access" in their condition part, and that appear inside the main function of the program, across source files *.c:
sgrep '"if" not in ("/*" quote "*/" or ("\n#" .. "\n")) \
.. ("(" .. ")") containing "access" \
in ("main(" .. ("{" .. "}")) \
.. ("{" .. "}" or ";")' *.c
so yeah. as you can see, these complicated conditions get pretty illegible fast ๐ญ the way to fix that? carefully designed macros, periodt. macros make expressing queries so much easier.
for example, you could drop these m4 macro processor definitions into 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)
.. ("(" .. ")")))
and then that same query from before becomes so much more intuitive to write:
sgrep -p m4 -f c.macros -e 'IF_COND containing "access"\
in ( "main(" .. BLOCK ) .. (BLOCK or ";")' *.c
like. look at that. chef's kiss ๐โจ
โก OPTIMIZATION โก
bestie, sgrep is not out here doing the same work twice. it performs common subexpression elimination on the query expression, so recurring sub-expressions get evaluated only once. no cap. ๐ง
for example, in this expression:
'(" " or "\n" or "\t") .. (" " or "\n" or "\t")'
the sub-expression
'(" " or "\n" or "\t")'
is evaluated only one. ๐ (yes, "only one". the original said it like that and honestly? iconic. we keep it.)
๐ฉบ DIAGNOSTICS ๐ฉบ
okay so the exit status tea โ:
- exit status is 0 if any matching regions are found
- exit status is 1 if none are found
- exit status is 2 for syntax errors or inaccessible files โ and yes, even if matching regions were found, you still get a 2. the error wins. periodt.
๐ฑ ENVIRONMENT ๐ฑ
you can set your own default options for sgrep as the value of the environment variable SGREPOPT. your personal defaults, your rules ๐
for example, running:
setenv SGREPOPT '-p m4 -o %r\n'
makes sgrep apply the m4 preprocessor to the expression, and display each output region as such, followed by a line feed. cute, right? ๐ธ
๐ FILES ๐
sgrep tries to read the contents of these files:
$HOME/.sgreprc/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" ))
๐ฎ FUTURE EXTENSIONS ๐ฎ
things that don't exist yet but honestly should ๐:
- Regular expressions (The most important missing feature)
- Built-in macro preprocessor
- More operations
- Indexing for large static texts
the first one is the most important missing feature. we're all waiting. patiently. mostly. ๐ญ
๐ AUTHORS ๐
Jani Jaakkola and Pekka Kilpelainen, University of Helsinki, Department of Computer Science, 1995. legends, fr fr ๐ซถ
๐ BUGS ๐
listen, we love her, but:
sgrepmay use lots of memory when evaluating complex queries on big files. like, a lot. be careful bestie.- when
sgrepreads its input text from a pipe, it copies it to a temporary file. sgrepdoes not have regular expressions in search patterns.
that last one is giving broken heart ๐ but we move.
๐ SEE ALSO ๐
awk(1),ed(1),grep(1)- sgrep home page at
http://www.cs.helsinki.fi/~jjaakkol/sgrep.html
and that's the whole page, bestie!! ๐ this lil manual is SGREP(1), and you can peep it whenever you need a vibe check on regions, queries and macros. go forth and sgrep responsibly ๐
โจ๐
๐ฆ where this page comes from
- debian trixie: sgrep 1.94a-7
- ubuntu questing: sgrep 1.94a-7
- ubuntu resolute: sgrep 1.94a-7build1
- ubuntu stonking: sgrep 1.94a-8 ยท GPL-2.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms