grep

Grep 搜索以 FILE 命名的文件输入 (或者是标准输入,如果没有指定文件名,或者给出的文件名是 - 的话),寻找含有与给定的模式 PATTERN 相匹配的内容的行。默认情况下, grep 将把含有匹配内容的行打印出来。

AD:


    NAME

    grep, egrep, fgrep - 打印匹配给定模式的行  

    总览 SYNOPSIS

    grep [options] PATTERN [FILE...]
    grep [options] [-e PATTERN | -f FILE] [FILE...]  

    描述 DESCRIPTION

    Grep 搜索以 FILE 命名的文件输入 (或者是标准输入,如果没有指定文件名,或者给出的文件名是 - 的话),寻找含有与给定的模式 PATTERN 相匹配的内容的行。默认情况下, grep 将把含有匹配内容的行打印出来。

    另外,也可以使用两个变种程序 egrepfgrepEgrepgrep -E 相同。 Fgrepgrep -F 相同。  

    选项 OPTIONS

    -A NUM, --after-context= NUM
    打印出紧随匹配的行之后的下文 NUM 行。在相邻的匹配组之间将会打印内容是 -- 的一行。
    -a, --text
    将一个二进制文件视为一个文本文件来处理;它与 --binary-files=text 选项等价。
    -B NUM, --before-context= NUM
    打印出匹配的行之前的上文 NUM 行。在相邻的匹配组之间将会打印内容是 -- 的一行。
    -C NUM, --context= NUM
    打印出匹配的行的上下文前后各 NUM 行。在相邻的匹配组之间将会打印内容是 -- 的一行。
    -b, --byte-offset
    在输出的每行前面同时打印出当前行在输入文件中的字节偏移量。
    --binary-files= TYPE
    如果一个文件的起始几个字节表明文件包含二进制数据,那么假定文件是 TYPE 类型的。默认情况下, TYPE binary ,并且 grep 一般会输出一个一行的消息说一个二进制文件匹配,或者如果没有匹配的话就没有消息输出。如果类型 TYPEwithout-match ,那么 grep 假定二进制文件不会匹配;这样做与 -I 选项等价。如果类型 TYPEtext ,那么 grep 将一个二进制文件视为文本文件来处理;它与 -a 选项等价。 警告: grep --binary-files=text 可能会输出二进制的无用内容。如果输出设备是一个终端,并且终端的驱动将这些输出中的一些当作命令,可能会带来恶劣的副作用。
    --colour[= WHEN] , --color[= WHEN]
    在匹配的行周围以 GREP_COLOR 环境变量中指定的记号来标记。WHEN 可以是 `never', `always', 或是 `auto'。
    -c, --count
    禁止通常的输出;作为替代,为每一个输入文件打印一个匹配的行的总数。如果使用 -v, --invert-match 选项 (参见下面),将是不匹配的行的总数。
    -D ACTION, --devices= ACTION
    如果输入文件是一个设备,FIFO 或是套接字 (socket) ,使用动作 ACTION 来处理它。默认情况下,动作 ACTIONread ,意味着设备将视为普通文件那样来读。如果动作 ACTIONskip ,将不处理而直接跳过设备。
    -d ACTION, --directories= ACTION
    如果输入文件是一个目录,使用动作 ACTION 来处理它。默认情况下,动作 ACTIONread ,意味着目录将视为普通文件那样来读。如果动作 ACTIONskip ,将不处理而直接跳过目录。如果动作 ACTION recursegrep 将递归地读每一目录下的所有文件。这样做和 -r 选项等价。
    -E, --extended-regexp
    将模式 PATTERN 作为一个扩展的正则表达式来解释 (参见下面)。
    -e PATTERN, --regexp= PATTERN
    使用模式 PATTERN 作为模式;在保护以 - 为起始的模式时有用。
    -F, --fixed-strings
    将模式 PATTERN 视为一个固定的字符串的列表,用新行 (newlines) 分隔,只要匹配其中之一即可。
    -P, --perl-regexp
    将模式 PATTERN 作为一个 Perl 正则表达式来解释。
    -f FILE, --file= FILE
    从文件 FILE 中获取模式,每行一个。空文件含有0个模式,因此不匹配任何东西。
    -G, --basic-regexp
    将模式 PATTERN 作为一个基本的正则表达式 (参见下面) 来解释。这是默认值。
    -H, --with-filename
    为每个匹配打印文件名。
    -h, --no-filename
    当搜索多个文件时,禁止在输出的前面加上文件名前缀。
    --help
    输出一个简短的帮助信息。
    -I
    处理一个二进制文件,但是认为它不包含匹配的内容。这和 --binary-files=without-match 选项等价。
    -i, --ignore-case
    忽略模式 PATTERN 和输入文件中的大小写的分别。
    -L, --files-without-match
    禁止通常的输出;作为替代,打印出每个在通常情况下不会产生输出的输入文件的名字。对每个文件的扫描在遇到第一个匹配的时候就会停止。
    -l, --files-with-matches
    禁止通常的输出;作为替代,打印出每个在通常情况下会产生输出的输入文件的名字。对每个文件的扫描在遇到第一个匹配的时候就会停止。
    -m NUM, --max-count= NUM
    在找到 NUM 个匹配的行之后,不再读这个文件。如果输入是来自一个普通文件的标准输入,并且已经输出了 NUM 个匹配的行, grep 保证标准输入被定位于退出时的最后一次匹配的行之后,不管是否指定了要输出紧随的下文的行。这样可以使一个调用程序恢复搜索。当 grepNUM 个匹配的行之后停止,它会输出任何紧随的下文的行。当使用了 -c--count 选项的时候, grep 不会输出比 NUM 更多的行。当指定了 -v--invert-match 选项的时候, grep 会在输出 NUM 个不匹配的行之后停止。
    --mmap
    如果可能的话,使用 mmap(2) 系统调用来读取输入,而不是默认的 read(2) 系统调用。在一些情况下, --mmap 提供较好的性能。但是,如果一个输入文件在 grep 正在操作时大小发生变化,或者如果发生了一个 I/O 错误, --mmap 可能导致不可知的行为 (包括core dumps)。
    -n, --line-number
    在输出的每行前面加上它所在的文件中它的行号。
    -o, --only-matching
    只显示匹配的行中与 PATTERN 相匹配的部分。
    --label= LABEL
    将实际上来自标准输入的输入视为来自输入文件 LABEL 。这对于 zgrep 这样的工具非常有用,例如: gzip -cd foo.gz |grep --label=foo something
    --line-buffering
    使用行缓冲,it can be a performance penality.
    -q, --quiet, --silent
    安静。不向标准输出写任何东西。如果找到任何匹配的内容就立即以状态值 0 退出,即使检测到了错误。参见 -s --no-messages 选项。
    -R, -r, --recursive
    递归地读每一目录下的所有文件。这样做和 -d recurse 选项等价。
    --include=PATTERN
    仅仅在搜索匹配 PATTERN 的文件时在目录中递归搜索。
    --exclude=PATTERN
    在目录中递归搜索,但是跳过匹配 PATTERN 的文件。
    -s, --no-messages
    禁止输出关于文件不存在或不可读的错误信息。对于可移植性需要注意:与 GNU grep 不同,传统的 grep 不遵守 POSIX.2 规范,因为传统的 grep 缺少一个 -q 选项,而它的 -s 选项与 GNU grep-q 选项行为相似。需要可移植到传统 grep 的 shell 脚本应当避免使用 -q-s 选项,而应当将输出重定向到 /dev/null 。
    -U, --binary
    将文件视为二进制。默认情况下,在 MS-DOS 和 MS-Windows 系统中, grep 通过从文件中读取头部的 32kB 内容来判断它的文件类型。如果 grep 判断文件是一个文本文件,它将原始文件内容中的 CR 字符去除 (使得含有 ^ $ 的正则表达式可以正常工作)。指定 -U 将不进行这些工作,而使所有文件保持不变地读取并传递给匹配机制。如果文件是一个以 CR/LF 换行的文本文件,这样作将导致一些正则表达式失败。这个选项在 MS-DOS 和 MS-Windows 之外的系统中无效。
    -u, --unix-byte-offsets
    报告 Unix 风格的字节偏移量。这个开关使得 grep 报告字节偏移量时,将文件作为 Unix 风格的文本文件看待,也就是说将 CR 字符去掉。这将产生与在一台 Unix 主机上运行 grep 完全相同的结果。除非同时使用 -b 选项,否则这个选项无效。这个选项在 MS-DOS 和 MS-Windows 之外的系统中无效。
    -V, --version
    向标准错误输出打印 grep 的版本号。版本号应当包含在所有的 bug 报告中 (参见下面)。
    -v, --invert-match
    改变匹配的意义,只选择不匹配的行。
    -w, --word-regexp
    只选择含有能组成完整的词的匹配的行。判断方法是匹配的子字符串必须是一行的开始,或者是在一个不可能是词的组成的字符之后。与此相似,它必须是一行的结束,或者是在一个不可能是词的组成的字符之前。词的组成字符是字母,数字,还有下划线。
    -x, --line-regexp
    只选择能匹配完整一行的匹配。
    -y
    -i 的同义词,废弃不用。
    -Z, --null
    输出一个全零字节 ( ASCII 码中的 NUL 字符) 而不是一般情况下输出在文件名之后的字符。例如, grep -lZ 在每个文件名之后输出一个全零字节而不是普通的新行符。这个选项使得输出清楚明白,即使文件名的表示中包含特殊字符比如新行符。这个选项可以与命令 find -print0, perl -0, sort -z, 和 xargs -0 一起使用,来处理任意的文件名,即使是那些含有新行符的文件名。

    正则表达式 REGULAR EXPRESSIONS

    一个正则表达式是一个描述了一个字符串集合的模式。正则表达式的构造类似于算术表达式,使用各种各样的操作符来将更小的表达式连在一起。

    Grep 能理解两种不同版本的正则表达式语法:``basic'' 和 ``extended''。在 GNU grep 中,两种语法可以实现的功能是没有区别的。在其他实现中,基本 (basic) 正则表达式表达能力要弱一点。下面的描述适用于扩展的 (extended) 正则表达式,它与基本正则表达式的区别会在最后做一个总结。

    基本的构造块是匹配单个字符的正则表达式。大部分字符,包括所有字母和数字,是匹配它们自身的正则表达式。任何具有特殊含义的元字符可以通过前置一个反斜杠来引用。(may be quoted by preceding it with a backslash.)

    方括号表达式 (bracket) 是一个字符序列,放在 [] 当中。它匹配序列中的任何一个字符;如果序列中的第一个字符是脱字符 (caret) ^ 那么它匹配 不在 序列中的任何一个字符。例如,正则表达式 [0123456789] 匹配任何一个数字。

    在方括号表达式之中,一个 范围表达式 (range) 由两个字符组成,中间用一个连字符 (hyphen) 分隔。它匹配在这两个字符之间的任何一个字符,使用本地化的序列顺序和字符集。(that sorts between the two characters,inclusive, using the locale's collating sequence and character set.) 例如,在默认的 C locale中, [a-d][abcd] 等价。典型的,许多 locale 将字符以字典顺序排序,在这些 locale 中, [a-d] 不与 [abcd] 等价;例如它可能与 [aBbCcDd] 等价。要获得传统的对方括号表达式的解释,可以设定环境变量 LC_ALL 值为 C 来使用 locale C 。

    最后,在方括号表达式中有一些预定义的字符类,如下所示。它们的名字是自说明的,它们是 [:alnum:](字母和数字), [:alpha:](字母), [:cntrl:](), [:digit:](数字), [:graph:](), [:lower:](小写字母), [:print:](可打印字符), [:punct:](), [:space:](空格), [:upper:](大写字母), 和 [:xdigit:] 。例如, [[:alnum:]] 意思是 [0-9A-Za-z] ,但是后一种表示方法依赖于 locale C 和ASCII 字符编码,而前一种是与 locale 和字符集无关的。(注意这些字符类名中的方括号也是符号名称的一部分,必须包含在用来为序列定界的方括号之中。)

    大多数元字符处于序列中时会失去它们的特殊意义。为了包含一个字面意义 (literal) 的 ] ,需要将它放在序列的最前。与此相似,为了包含一个字面意义 (literal) 的 ^ ,需要将它放在除了序列最前之外的其他位置。最后,为了包含一个字面意义 (literal) 的 - ,需要将它放在序列最后。

    句点符 (period) . 匹配任何一个字符。符号 \w[[:alnum:]] 的同义词, \W[^[:alnum]] 的同义词。

    脱字符 (caret) ^ 和美元标记 (dollar) $ 分别是匹配一行的首部和尾部的空字串的元字符。符号 \<\> 分别是匹配一个词的首部和尾部的空字串的元字符。符号 \b 匹配一个词边缘 (edge) 的空字串,符号 \B 匹配 处于一个词的边缘的空字串。

    一个正则表达式后面可以跟随多种重复操作符之一。

    ?
    先前的项是可选的,最多匹配一次。
    *
    先前的项可以匹配零次或多次。
    +
    先前的项可以匹配一次或多次。
    { n }
    先前的项将匹配恰好 n 次。
    { n ,}
    先前的项可以匹配 n 或更多次。
    { n , m }
    先前的项将匹配至少 n 词,但是不会超过 m 次。

    两个正则表达式可以连接到一起;得出的正则表达式可以匹配任何由两个分别匹配连接前的子表达式的子字符串连接而成的字符串。

    两个正则表达式可以用中缀操作符 | 联合到一起,得出的正则表达式可以匹配任何匹配联合前的任何一个子表达式的字符串。

    重复操作符的优先级比连接高,接下来又比选择的优先级高。一个完整的子表达式可以用圆括号 (parentheses) 括住来超越这些优先级规则。(to override these precedence rules.)

    反向引用 \n 中, n 是一个数字,匹配正则表达式中,以第 n 个圆括号括住的子表达式已匹配的子字符串。

    在基本正则表达式中,元字符 ?, +, {, |, (, 和 ) 丧失了它们的特殊意义;作为替代,使用加反斜杠的 (backslash) 版本 \?, \+, \{, \|, \(, 和 \)

    传统的 egrep 不支持元字符 { ,并且一些 egrep 的实现通过支持 \{ 来代替它,因此可移植的脚本应当避免在 egrep 中使用 { 模式,应当使用 [{] 来匹配一个字面意义 (literal) 的 {

    GNU egrep 通过假设如果 { 处于 an invalid interval specification 的起始,就不是一个特殊字符,来支持传统的用法。例如,shell 命令 egrep '{1' 将会搜索这个两字符的字符串 {1 而不是报告在正则表达式中发生了语法错误。POSIX.2 允许这个行为,将其视为一个扩展,但是可移植的脚本应当避免使用它。  

    环境变量 ENVIRONMENT VARIABLES

    Grep 的行为受下列环境变量影响。

    一个 locale LC_foo 是通过按下面的顺序, LC_ALL, LC_foo, LANG, 检查这三个环境变量的取值而确定的。设置了的第一个变量指定了 locale。例如,如果 LC_ALL 没有设置,但是 LC_MESSAGES 设置为 pt_BR ,那么巴西的葡萄牙语 (Brazilian Portuguese) 将用作 LC_MESSAGES locale 的值。如果没有设置这其中任何一个环境变量,或者没有安装所设置的 locale 目录,或者如果 grep 没有将国家和语言支持 (national language support (NLS)) 编译在内,将默认使用 locale C。

    GREP_OPTIONS
    这个变量指定了将放在所有显式指定的选项之前的默认选项。例如,如果 GREP_OPTIONS'--binary-files=without-match --directories=skip' 的话, grep 将像已经在任何显式指定的选项之前指定了 --binary-files=without-match--directories=skip 选项那样来运作。选项以空白 (whitespace) 分隔。一个反斜杠 (backslash) 使得下一个字符转义 (escape),因此可以用来指定一个含有空白或者反斜杠的选项。
    GREP_COLOR
    指定用来高亮显示的标记。
    LC_ALL, LC_COLLATE, LANG
    这些变量指定了 locale LC_COLLATE ,决定了解释类似 [a-z] 的范围表达式时的序列顺序 (collating sequence) 。
    LC_ALL, LC_CTYPE, LANG
    这些选项指定了 locale LC_CTYPE ,决定了字符的类型,例如,哪些字符是空白 (whitespace) 。
    LC_ALL, LC_MESSAGES, LANG
    这些选项指定了 locale LC_MESSAGES ,决定了 grep 的消息使用的语言。默认的 locale C 使用美国英语的消息。
    POSIXLY_CORRECT
    如果设置了的话, grep 将像 POSIX.2 要求的那样来运作;否则, grep 将像其他 GNU 程序一样来运作。 POSIX.2 要求文件名之后的选项必须视为文件名;默认情况下,这些选项被交换到操作数列表的前面,被当作选项来处理。同时, POSIX.2 要求不可识别的选项在诊断消息中表示为 ``illegal'',但是既然它们没有真正触犯法律,因此默认情况下它们在诊断 (diagnose) 消息中表示为 ``invalid''。 POSIXLY_CORRECT 同时禁止了下面描述的 _ N _GNU_nonoption_argv_flags_
    _ N _GNU_nonoption_argv_flags_
    (这里 Ngrep's 数字形式的进程ID。) 如果这个环境变量的值的第 i 个字符是 1 ,那么不将 grep 的第 i 个操作数视为一个选项,即使它看上去像。shell 可以将这个变量设置在它运行的每个命令的环境中,指定哪个操作数是文件名通配符扩展的结果,因此不应当被视为选项。这个行为只有在使用 GNU C 库时有效,并且只有在 POSIXLY_CORRECT 没有设置的时候。

    NAME

    grep, egrep, fgrep - print lines matching a pattern  

    SYNOPSIS

    grep [options] PATTERN [FILE...]
    grep [options] [-e PATTERN | -f FILE] [FILE...]  

    DESCRIPTION

    Grep searches the named input FILEs (or standard input if no files are named, or the file name - is given) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

    In addition, two variant programs egrep and fgrep are available. Egrep is the same as grep -E. Fgrep is the same as grep -F.  

    OPTIONS

    -A NUM, --after-context= NUM
    Print NUM lines of trailing context after matching lines. Places a line containing -- between contiguous groups of matches.
    -a, --text
    Process a binary file as if it were text; this is equivalent to the --binary-files=text option.
    -B NUM, --before-context= NUM
    Print NUM lines of leading context before matching lines. Places a line containing -- between contiguous groups of matches.
    -C NUM, --context= NUM
    Print NUM lines of output context. Places a line containing -- between contiguous groups of matches.
    -b, --byte-offset
    Print the byte offset within the input file before each line of output.
    --binary-files= TYPE
    If the first few bytes of a file indicate that the file contains binary data, assume that the file is of type TYPE. By default, TYPE is binary, and grep normally outputs either a one-line message saying that a binary file matches, or no message if there is no match. If TYPE is without-match, grep assumes that a binary file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. Warning: grep --binary-files=text might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands.
    --colour[= WHEN] , --color[= WHEN]
    Surround the matching string with the marker find in GREP_COLOR environment variable. WHEN may be `never', `always', or `auto'
    -c, --count
    Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see below), count non-matching lines.
    -D ACTION, --devices= ACTION
    If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped.
    -d ACTION, --directories= ACTION
    If an input file is a directory, use ACTION to process it. By default, ACTION is read, which means that directories are read just as if they were ordinary files. If ACTION is skip, directories are silently skipped. If ACTION is recurse, grep reads all files under each directory, recursively; this is equivalent to the -r option.
    -E, --extended-regexp
    Interpret PATTERN as an extended regular expression (see below).
    -e PATTERN, --regexp= PATTERN
    Use PATTERN as the pattern; useful to protect patterns beginning with -.
    -F, --fixed-strings
    Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
    -P, --perl-regexp
    Interpret PATTERN as a Perl regular expression.
    -f FILE, --file= FILE
    Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing.
    -G, --basic-regexp
    Interpret PATTERN as a basic regular expression (see below). This is the default.
    -H, --with-filename
    Print the filename for each match.
    -h, --no-filename
    Suppress the prefixing of filenames on output when multiple files are searched.
    --help
    Output a brief help message.
    -I
    Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option.
    -i, --ignore-case
    Ignore case distinctions in both the PATTERN and the input files.
    -L, --files-without-match
    Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.
    -l, --files-with-matches
    Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.
    -m NUM, --max-count= NUM
    Stop reading a file after NUM matching lines. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines.
    --mmap
    If possible, use the mmap(2) system call to read input, instead of the default read(2) system call. In some situations, --mmap yields better performance. However, --mmap can cause undefined behavior (including core dumps) if an input file shrinks while grep is operating, or if an I/O error occurs.
    -n, --line-number
    Prefix each line of output with the line number within its input file.
    -o, --only-matching
    Show only the part of a matching line that matches PATTERN.
    --label= LABEL
    Displays input actually coming from standard input as input coming from file LABEL. This is especially useful for tools like zgrep, e.g. gzip -cd foo.gz |grep --label=foo something
    --line-buffered
    Use line buffering, it can be a performance penality.
    -q, --quiet, --silent
    Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option.
    -R, -r, --recursive
    Read all files under each directory, recursively; this is equivalent to the -d recurse option.
    --include=PATTERN
    Recurse in directories only searching file matching PATTERN.
    --exclude=PATTERN
    Recurse in directories skip file matching PATTERN.
    -s, --no-messages
    Suppress error messages about nonexistent or unreadable files. Portability note: unlike GNU grep, traditional grep did not conform to POSIX.2, because traditional grep lacked a -q option and its -s option behaved like GNU grep's -q option. Shell scripts intended to be portable to traditional grep should avoid both -q and -s and should redirect output to /dev/null instead.
    -U, --binary
    Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses the file type by looking at the contents of the first 32KB read from the file. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows.
    -u, --unix-byte-offsets
    Report Unix-style byte offsets. This switch causes grep to report byte offsets as if the file were Unix-style text file, i.e. with CR characters stripped off. This will produce results identical to running grep on a Unix machine. This option has no effect unless -b option is also used; it has no effect on platforms other than MS-DOS and MS-Windows.
    -V, --version
    Print the version number of grep to standard error. This version number should be included in all bug reports (see below).
    -v, --invert-match
    Invert the sense of matching, to select non-matching lines.
    -w, --word-regexp
    Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore.
    -x, --line-regexp
    Select only those matches that exactly match the whole line.
    -y
    Obsolete synonym for -i.
    -Z, --null
    Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters.

    REGULAR EXPRESSIONS

    A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions.

    Grep understands two different versions of regular expression syntax: ``basic'' and ``extended.'' In GNU grep, there is no difference in available functionality using either syntax. In other implementations, basic regular expressions are less powerful. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards.

    The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any metacharacter with special meaning may be quoted by preceding it with a backslash.

    A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list; if the first character of the list is the caret ^ then it matches any character not in the list. For example, the regular expression [0123456789] matches any single digit.

    Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C.

    Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means [0-9A-Za-z], except the latter form depends upon the C locale and the ASCII character encoding, whereas the former is independent of locale and character set. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket list.) Most metacharacters lose their special meaning inside lists. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last.

    The period . matches any single character. The symbol \w is a synonym for [[:alnum:]] and \W is a synonym for [^[:alnum]].

    The caret ^ and the dollar sign $ are metacharacters that respectively match the empty string at the beginning and end of a line. The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word.

    A regular expression may be followed by one of several repetition operators:

    ?
    The preceding item is optional and matched at most once.
    *
    The preceding item will be matched zero or more times.
    +
    The preceding item will be matched one or more times.
    { n }
    The preceding item is matched exactly n times.
    { n ,}
    The preceding item is matched n or more times.
    { n , m }
    The preceding item is matched at least n times, but not more than m times.

    Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated subexpressions.

    Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either subexpression.

    Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole subexpression may be enclosed in parentheses to override these precedence rules.

    The backreference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression.

    In basic regular expressions the metacharacters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).

    Traditional egrep did not support the { metacharacter, and some egrep implementations support \{ instead, so portable scripts should avoid { in egrep patterns and should use [{] to match a literal {.

    GNU egrep attempts to support traditional usage by assuming that { is not special if it would be the start of an invalid interval specification. For example, the shell command egrep '{1' searches for the two-character string {1 instead of reporting a syntax error in the regular expression. POSIX.2 allows this behavior as an extension, but portable scripts should avoid it.  

    ENVIRONMENT VARIABLES

    Grep's behavior is affected by the following environment variables.

    A locale LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then Brazilian Portuguese is used for the LC_MESSAGES locale. The C locale is used if none of these environment variables are set, or if the locale catalog is not installed, or if grep was not compiled with national language support (NLS).

    GREP_OPTIONS
    This variable specifies default options to be placed in front of any explicit options. For example, if GREP_OPTIONS is '--binary-files=without-match --directories=skip', grep behaves as if the two options --binary-files=without-match and --directories=skip had been specified before any explicit options. Option specifications are separated by whitespace. A backslash escapes the next character, so it can be used to specify an option containing whitespace or a backslash.
    GREP_COLOR
    Specifies the marker for highlighting.
    LC_ALL, LC_COLLATE, LANG
    These variables specify the LC_COLLATE locale, which determines the collating sequence used to interpret range expressions like [a-z].
    LC_ALL, LC_CTYPE, LANG
    These variables specify the LC_CTYPE locale, which determines the type of characters, e.g., which characters are whitespace.
    LC_ALL, LC_MESSAGES, LANG
    These variables specify the LC_MESSAGES locale, which determines the language that grep uses for messages. The default C locale uses American English messages.
    POSIXLY_CORRECT
    If set, grep behaves as POSIX.2 requires; otherwise, grep behaves more like other GNU programs. POSIX.2 requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX.2 requires that unrecognized options be diagnosed as ``illegal'', but since they are not really against the law the default is to diagnose them as ``invalid''. POSIXLY_CORRECT also disables _ N _GNU_nonoption_argv_flags_, described below.
    _ N _GNU_nonoption_argv_flags_
    (Here N is grep's numeric process ID.) If the ith character of this environment variable's value is 1, do not consider the ith operand of grep to be an option, even if it appears to be one. A shell can put this variable in the environment for each command it runs, specifying which operands are the results of file name wildcard expansion and therefore should not be treated as options. This behavior is available only with the GNU C library, and only when POSIXLY_CORRECT is not set.
    • 0
      点赞
    • 0
      收藏
      觉得还不错? 一键收藏
    • 0
      评论

    “相关推荐”对你有帮助么?

    • 非常没帮助
    • 没帮助
    • 一般
    • 有帮助
    • 非常有帮助
    提交
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值