Linux 文本查找工具——grep、egrep、fgrep

2023-12-25 21:08

本文主要是介绍Linux 文本查找工具——grep、egrep、fgrep,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

* grep 命令

        用来搜索和制定字符串或者模式相匹配的行

命令格式

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

常用选项(OPTION)

-e    --regexp

-i    --ignore-case

-r    --recursive

-rl    --files-with-matches

-w    --word-regexp

-c    --count

-n    --line-number

-v    --invert-match

--color

grep_help

$ grep --help
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: grep -i 'hello world' menu.h main.cRegexp selection and interpretation:-E, --extended-regexp     PATTERN is an extended regular expression (ERE)-F, --fixed-strings       PATTERN is a set of newline-separated fixed strings-G, --basic-regexp        PATTERN is a basic regular expression (BRE)-P, --perl-regexp         PATTERN is a Perl regular expression-e, --regexp=PATTERN      use PATTERN for matching-f, --file=FILE           obtain PATTERN from FILE-i, --ignore-case         ignore case distinctions-w, --word-regexp         force PATTERN to match only whole words-x, --line-regexp         force PATTERN to match only whole lines-z, --null-data           a data line ends in 0 byte, not newlineMiscellaneous:-s, --no-messages         suppress error messages-v, --invert-match        select non-matching lines-V, --version             display version information and exit--help                display this help text and exitOutput control:-m, --max-count=NUM       stop after NUM matches-b, --byte-offset         print the byte offset with output lines-n, --line-number         print line number with output lines--line-buffered       flush output on every line-H, --with-filename       print the file name for each match-h, --no-filename         suppress the file name prefix on output--label=LABEL         use LABEL as the standard input file name prefix-o, --only-matching       show only the part of a line matching PATTERN-q, --quiet, --silent     suppress all normal output--binary-files=TYPE   assume that binary files are TYPE;TYPE is 'binary', 'text', or 'without-match'-a, --text                equivalent to --binary-files=text-I                        equivalent to --binary-files=without-match-d, --directories=ACTION  how to handle directories;ACTION is 'read', 'recurse', or 'skip'-D, --devices=ACTION      how to handle devices, FIFOs and sockets;ACTION is 'read' or 'skip'-r, --recursive           like --directories=recurse-R, --dereference-recursivelikewise, but follow all symlinks--include=FILE_PATTERNsearch only files that match FILE_PATTERN--exclude=FILE_PATTERNskip files and directories matching FILE_PATTERN--exclude-from=FILE   skip files matching any file pattern from FILE--exclude-dir=PATTERN directories that match PATTERN will be skipped.-L, --files-without-match print only names of FILEs containing no match-l, --files-with-matches  print only names of FILEs containing matches-c, --count               print only a count of matching lines per FILE-T, --initial-tab         make tabs line up (if needed)-Z, --null                print 0 byte after FILE nameContext control:-B, --before-context=NUM  print NUM lines of leading context-A, --after-context=NUM   print NUM lines of trailing context-C, --context=NUM         print NUM lines of output context-NUM                      same as --context=NUM--group-separator=SEP use SEP as a group separator--no-group-separator  use empty string as a group separator--color[=WHEN],--colour[=WHEN]       use markers to highlight the matching strings;WHEN is 'always', 'never', or 'auto'-U, --binary              do not strip CR characters at EOL (MSDOS/Windows)-u, --unix-byte-offsets   report offsets as if CRs were not there(MSDOS/Windows)'egrep' means 'grep -E'.  'fgrep' means 'grep -F'.
Direct invocation as either 'egrep' or 'fgrep' is deprecated.
When FILE is -, read standard input.  With no FILE, read . if a command-line
-r is given, - otherwise.  If fewer than two FILEs are given, assume -h.
Exit status is 0 if any line is selected, 1 otherwise;
if any error occurs and -q is not given, the exit status is 2.Report bugs to: bug-grep@gnu.org
GNU Grep home page: <http://www.gnu.org/software/grep/>
General help using GNU software: <http://www.gnu.org/gethelp/>

grep_man

$ man grepGREP(1)                   BSD General Commands Manual                  GREP(1)NAMEgrep, egrep, fgrep, zgrep, zegrep, zfgrep -- file pattern searcherSYNOPSISgrep [-abcdDEFGHhIiJLlmnOopqRSsUVvwxZ] [-A num] [-B num] [-C[num]] [-e pattern] [-f file] [--binary-files=value][--color[=when]] [--colour[=when]] [--context[=num]] [--label] [--line-buffered] [--null] [pattern] [file ...]DESCRIPTIONThe grep utility searches any given input files, selecting lines that match one or more patterns.  By default, a patternmatches an input line if the regular expression (RE) in the pattern matches the input line without its trailing newline.An empty expression matches every line.  Each input line that matches at least one of the patterns is written to the stan-dard output.grep is used for simple patterns and basic regular expressions (BREs); egrep can handle extended regular expressions(EREs).  See re_format(7) for more information on regular expressions.  fgrep is quicker than both grep and egrep, but canonly handle fixed patterns (i.e. it does not interpret regular expressions).  Patterns may consist of one or more lines,allowing any of the pattern lines to match a portion of the input.zgrep, zegrep, and zfgrep act like grep, egrep, and fgrep, respectively, but accept input files compressed with thecompress(1) or gzip(1) compression utilities.The following options are available:-A num, --after-context=numPrint num lines of trailing context after each match.  See also the -B and -C options.-a, --textTreat all files as ASCII text.  Normally grep will simply print ``Binary file ... matches'' if files contain binarycharacters.  Use of this option forces grep to output lines matching the specified pattern.-B num, --before-context=numPrint num lines of leading context before each match.  See also the -A and -C options.-b, --byte-offsetThe offset in bytes of a matched pattern is displayed in front of the respective matched line.-C[num, --context=num]Print num lines of leading and trailing context surrounding each match.  The default is 2 and is equivalent to -A 2-B 2.  Note: no whitespace may be given between the option and its argument.-c, --countOnly a count of selected lines is written to standard output.--colour=[when, --color=[when]]Mark up the matching text with the expression stored in GREP_COLOR environment variable.  The possible values ofwhen can be `never', `always' or `auto'.-D action, --devices=actionSpecify the demanded action for devices, FIFOs and sockets.  The default action is `read', which means, that theyare read as if they were normal files.  If the action is set to `skip', devices will be silently skipped.-d action, --directories=actionSpecify the demanded action for directories.  It is `read' by default, which means that the directories are read inthe same manner as normal files.  Other possible values are `skip' to silently ignore the directories, and`recurse' to read them recursively, which has the same effect as the -R and -r option.-E, --extended-regexpInterpret pattern as an extended regular expression (i.e. force grep to behave as egrep).-e pattern, --regexp=patternSpecify a pattern used during the search of the input: an input line is selected if it matches any of the specifiedpatterns.  This option is most useful when multiple -e options are used to specify multiple patterns, or when apattern begins with a dash (`-').--excludeIf specified, it excludes files matching the given filename pattern from the search.  Note that --exclude patternstake priority over --include patterns, and if no --include pattern is specified, all files are searched that arenot excluded.  Patterns are matched to the full path specified, not only to the filename component.--exclude-dirIf -R is specified, it excludes directories matching the given filename pattern from the search.  Note that--exclude-dir patterns take priority over --include-dir patterns, and if no --include-dir pattern is specified, alldirectories are searched that are not excluded.-F, --fixed-stringsInterpret pattern as a set of fixed strings (i.e. force grep to behave as fgrep).-f file, --file=fileRead one or more newline separated patterns from file.  Empty pattern lines match every input line.  Newlines arenot considered part of a pattern.  If file is empty, nothing is matched.-G, --basic-regexpInterpret pattern as a basic regular expression (i.e. force grep to behave as traditional grep).-H      Always print filename headers with output lines.-h, --no-filenameNever print filename headers (i.e. filenames) with output lines.--help  Print a brief help message.-I      Ignore binary files.  This option is equivalent to --binary-file=without-match option.-i, --ignore-casePerform case insensitive matching.  By default, grep is case sensitive.--includeIf specified, only files matching the given filename pattern are searched.  Note that --exclude patterns take pri-ority over --include patterns.  Patterns are matched to the full path specified, not only to the filename compo-nent.--include-dirIf -R is specified, only directories matching the given filename pattern are searched.  Note that --exclude-dirpatterns take priority over --include-dir patterns.-J, --bz2decompressDecompress the bzip2(1) compressed file before looking for the text.-L, --files-without-matchOnly the names of files not containing selected lines are written to standard output.  Pathnames are listed onceper file searched.  If the standard input is searched, the string ``(standard input)'' is written.-l, --files-with-matchesOnly the names of files containing selected lines are written to standard output.  grep will only search a fileuntil a match has been found, making searches potentially less expensive.  Pathnames are listed once per filesearched.  If the standard input is searched, the string ``(standard input)'' is written.--mmap  Use mmap(2) instead of read(2) to read input, which can result in better performance under some circumstances butcan cause undefined behaviour.-m num, --max-count=numStop reading the file after num matches.-n, --line-numberEach output line is preceded by its relative line number in the file, starting at line 1.  The line number counteris reset for each file processed.  This option is ignored if -c, -L, -l, or -q is specified.--null  Prints a zero-byte after the file name.-O      If -R is specified, follow symbolic links only if they were explicitly listed on the command line.  The default isnot to follow symbolic links.-o, --only-matchingPrints only the matching part of the lines.-p      If -R is specified, no symbolic links are followed.  This is the default.-q, --quiet, --silentQuiet mode: suppress normal output.  grep will only search a file until a match has been found, making searchespotentially less expensive.-R, -r, --recursiveRecursively search subdirectories listed.-S      If -R is specified, all symbolic links are followed.  The default is not to follow symbolic links.-s, --no-messagesSilent mode.  Nonexistent and unreadable files are ignored (i.e. their error messages are suppressed).-U, --binarySearch binary files, but do not attempt to print them.-V, --versionDisplay version information and exit.-v, --invert-matchSelected lines are those not matching any of the specified patterns.-w, --word-regexpThe expression is searched for as a word (as if surrounded by `[[:<:]]' and `[[:>:]]'; see re_format(7)).-x, --line-regexpOnly input lines selected against an entire fixed string or regular expression are considered to be matching lines.-y      Equivalent to -i.  Obsoleted.-Z, -z, --decompressForce grep to behave as zgrep.--binary-files=valueControls searching and printing of binary files.  Options are binary, the default: search binary files but do notprint them; without-match: do not search binary files; and text: treat all files as text.--context[=num]Print num lines of leading and trailing context.  The default is 2.--line-bufferedForce output to be line buffered.  By default, output is line buffered when standard output is a terminal and blockbuffered otherwise.If no file arguments are specified, the standard input is used.ENVIRONMENTGREP_OPTIONS  May be used to specify default options that will be placed at the beginning of the argument list.  Backslash-escaping is not supported, unlike the behavior in GNU grep.EXIT STATUSThe grep utility exits with one of the following values:0     One or more lines were selected.1     No lines were selected.>1    An error occurred.EXAMPLESTo find all occurrences of the word `patricia' in a file:$ grep 'patricia' myfileTo find all occurrences of the pattern `.Pp' at the beginning of a line:$ grep '^\.Pp' myfileThe apostrophes ensure the entire expression is evaluated by grep instead of by the user's shell.  The caret `^' matchesthe null string at the beginning of a line, and the `\' escapes the `.', which would otherwise match any character.To find all lines in a file which do not contain the words `foo' or `bar':$ grep -v -e 'foo' -e 'bar' myfileA simple example of an extended regular expression:$ egrep '19|20|25' calendarPeruses the file `calendar' looking for either 19, 20, or 25.SEE ALSOed(1), ex(1), gzip(1), sed(1), re_format(7)STANDARDSThe grep utility is compliant with the IEEE Std 1003.1-2008 (``POSIX.1'') specification.The flags [-AaBbCDdGHhIJLmoPRSUVwZ] are extensions to that specification, and the behaviour of the -f flag when used withan empty pattern file is left undefined.All long options are provided for compatibility with GNU versions of this utility.Historic versions of the grep utility also supported the flags [-ruy].  This implementation supports those options; how-ever, their use is strongly discouraged.HISTORYThe grep command first appeared in Version 6 AT&T UNIX.BUGSThe grep utility does not normalize Unicode input, so a pattern containing composed characters will not match decomposedinput, and vice versa.BSD                              July 28, 2010                             BSD

* egrep

* fgrep

参考:

Linux基础 grep egrep fgrep 区别及用法_ss75710541_51CTO博客

shell中grep和egrep用法 - 知乎

grep和egrep的区别(shell通配符详解) - ..空白 - 博客园

​​​​​​grep与egrep_Nick-CSDN博客

grep、egrep命令用法 - tsw1107 - 博客园

linux里grep和egrep,fgrep的区别_xiaoxinyu316的专栏-CSDN博客_fgrep

Have Fun

这篇关于Linux 文本查找工具——grep、egrep、fgrep的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/536944

相关文章

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

Linux下进程的CPU配置与线程绑定过程

《Linux下进程的CPU配置与线程绑定过程》本文介绍Linux系统中基于进程和线程的CPU配置方法,通过taskset命令和pthread库调整亲和力,将进程/线程绑定到特定CPU核心以优化资源分配... 目录1 基于进程的CPU配置1.1 对CPU亲和力的配置1.2 绑定进程到指定CPU核上运行2 基于

golang程序打包成脚本部署到Linux系统方式

《golang程序打包成脚本部署到Linux系统方式》Golang程序通过本地编译(设置GOOS为linux生成无后缀二进制文件),上传至Linux服务器后赋权执行,使用nohup命令实现后台运行,完... 目录本地编译golang程序上传Golang二进制文件到linux服务器总结本地编译Golang程序

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

linux解压缩 xxx.jar文件进行内部操作过程

《linux解压缩xxx.jar文件进行内部操作过程》:本文主要介绍linux解压缩xxx.jar文件进行内部操作,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、解压文件二、压缩文件总结一、解压文件1、把 xxx.jar 文件放在服务器上,并进入当前目录#

Linux系统性能检测命令详解

《Linux系统性能检测命令详解》本文介绍了Linux系统常用的监控命令(如top、vmstat、iostat、htop等)及其参数功能,涵盖进程状态、内存使用、磁盘I/O、系统负载等多维度资源监控,... 目录toppsuptimevmstatIOStatiotopslabtophtopdstatnmon

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核