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

相关文章

windows和Linux安装Jmeter与简单使用方式

《windows和Linux安装Jmeter与简单使用方式》:本文主要介绍windows和Linux安装Jmeter与简单使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录Windows和linux安装Jmeter与简单使用一、下载安装包二、JDK安装1.windows设

Kali Linux安装实现教程(亲测有效)

《KaliLinux安装实现教程(亲测有效)》:本文主要介绍KaliLinux安装实现教程(亲测有效),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、下载二、安装总结一、下载1、点http://www.chinasem.cn击链接 Get Kali | Kal

linux服务之NIS账户管理服务方式

《linux服务之NIS账户管理服务方式》:本文主要介绍linux服务之NIS账户管理服务方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、所需要的软件二、服务器配置1、安装 NIS 服务2、设定 NIS 的域名 (NIS domain name)3、修改主

Linux实现简易版Shell的代码详解

《Linux实现简易版Shell的代码详解》本篇文章,我们将一起踏上一段有趣的旅程,仿照CentOS–Bash的工作流程,实现一个功能虽然简单,但足以让你深刻理解Shell工作原理的迷你Sh... 目录一、程序流程分析二、代码实现1. 打印命令行提示符2. 获取用户输入的命令行3. 命令行解析4. 执行命令

利用Python实现Excel文件智能合并工具

《利用Python实现Excel文件智能合并工具》有时候,我们需要将多个Excel文件按照特定顺序合并成一个文件,这样可以更方便地进行后续的数据处理和分析,下面我们看看如何使用Python实现Exce... 目录运行结果为什么需要这个工具技术实现工具的核心功能代码解析使用示例工具优化与扩展有时候,我们需要将

Python+PyQt5实现文件夹结构映射工具

《Python+PyQt5实现文件夹结构映射工具》在日常工作中,我们经常需要对文件夹结构进行复制和备份,本文将带来一款基于PyQt5开发的文件夹结构映射工具,感兴趣的小伙伴可以跟随小编一起学习一下... 目录概述功能亮点展示效果软件使用步骤代码解析1. 主窗口设计(FolderCopyApp)2. 拖拽路径

MySQL Workbench工具导出导入数据库方式

《MySQLWorkbench工具导出导入数据库方式》:本文主要介绍MySQLWorkbench工具导出导入数据库方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录mysql Workbench工具导出导入数据库第一步 www.chinasem.cn数据库导出第二步

ubuntu16.04如何部署dify? 在Linux上安装部署Dify的技巧

《ubuntu16.04如何部署dify?在Linux上安装部署Dify的技巧》随着云计算和容器技术的快速发展,Docker已经成为现代软件开发和部署的重要工具之一,Dify作为一款优秀的云原生应用... Dify 是一个基于 docker 的工作流管理工具,旨在简化机器学习和数据科学领域的多步骤工作流。它

C#实现查找并删除PDF中的空白页面

《C#实现查找并删除PDF中的空白页面》PDF文件中的空白页并不少见,因为它们有可能是作者有意留下的,也有可能是在处理文档时不小心添加的,下面我们来看看如何使用Spire.PDFfor.NET通过C#... 目录安装 Spire.PDF for .NETC# 查找并删除 PDF 文档中的空白页C# 添加与删

Linux高并发场景下的网络参数调优实战指南

《Linux高并发场景下的网络参数调优实战指南》在高并发网络服务场景中,Linux内核的默认网络参数往往无法满足需求,导致性能瓶颈、连接超时甚至服务崩溃,本文基于真实案例分析,从参数解读、问题诊断到优... 目录一、问题背景:当并发连接遇上性能瓶颈1.1 案例环境1.2 初始参数分析二、深度诊断:连接状态与