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

相关文章

python版本切换工具pyenv的安装及用法

《python版本切换工具pyenv的安装及用法》Pyenv是管理Python版本的最佳工具之一,特别适合开发者和需要切换多个Python版本的用户,:本文主要介绍python版本切换工具pyen... 目录Pyenv 是什么?安装 Pyenv(MACOS)使用 Homebrew:配置 shell(zsh

Python自动化提取多个Word文档的文本

《Python自动化提取多个Word文档的文本》在日常工作和学习中,我们经常需要处理大量的Word文档,本文将深入探讨如何利用Python批量提取Word文档中的文本内容,帮助你解放生产力,感兴趣的小... 目录为什么需要批量提取Word文档文本批量提取Word文本的核心技术与工具安装 Spire.Doc

Linux内核定时器使用及说明

《Linux内核定时器使用及说明》文章详细介绍了Linux内核定时器的特性、核心数据结构、时间相关转换函数以及操作API,通过示例展示了如何编写和使用定时器,包括按键消抖的应用... 目录1.linux内核定时器特征2.Linux内核定时器核心数据结构3.Linux内核时间相关转换函数4.Linux内核定时

Linux镜像文件制作方式

《Linux镜像文件制作方式》本文介绍了Linux镜像文件制作的过程,包括确定磁盘空间布局、制作空白镜像文件、分区与格式化、复制引导分区和其他分区... 目录1.确定磁盘空间布局2.制作空白镜像文件3.分区与格式化1) 分区2) 格式化4.复制引导分区5.复制其它分区1) 挂载2) 复制bootfs分区3)

Python+wxPython开发一个文件属性比对工具

《Python+wxPython开发一个文件属性比对工具》在日常的文件管理工作中,我们经常会遇到同一个文件存在多个版本,或者需要验证备份文件与源文件是否一致,下面我们就来看看如何使用wxPython模... 目录引言项目背景与需求应用场景核心需求运行结果技术选型程序设计界面布局核心功能模块关键代码解析文件大

Linux服务器数据盘移除并重新挂载的全过程

《Linux服务器数据盘移除并重新挂载的全过程》:本文主要介绍在Linux服务器上移除并重新挂载数据盘的整个过程,分为三大步:卸载文件系统、分离磁盘和重新挂载,每一步都有详细的步骤和注意事项,确保... 目录引言第一步:卸载文件系统第二步:分离磁盘第三步:重新挂载引言在 linux 服务器上移除并重新挂p

Linux下屏幕亮度的调节方式

《Linux下屏幕亮度的调节方式》文章介绍了Linux下屏幕亮度调节的几种方法,包括图形界面、手动调节(使用ACPI内核模块)和外接显示屏调节,以及自动调节软件(CaliseRedshift和Reds... 目录1 概述2 手动调节http://www.chinasem.cn2.1 手动屏幕调节2.2 外接显

Linux(centos7)虚拟机没有IP问题及解决方案

《Linux(centos7)虚拟机没有IP问题及解决方案》文章介绍了在CentOS7中配置虚拟机网络并使用Xshell连接虚拟机的步骤,首先,检查并配置网卡ens33的ONBOOT属性为yes,然后... 目录输入查看ZFhrxIP命令:ip addr查看,没有虚拟机IP修改ens33配置文件重启网络Xh

linux实现对.jar文件的配置文件进行修改

《linux实现对.jar文件的配置文件进行修改》文章讲述了如何使用Linux系统修改.jar文件的配置文件,包括进入文件夹、编辑文件、保存并退出编辑器,以及重新启动项目... 目录linux对.jar文件的配置文件进行修改第一步第二步 第三步第四步总结linux对.jar文件的配置文件进行修改第一步进

linux ssh如何实现增加访问端口

《linuxssh如何实现增加访问端口》Linux中SSH默认使用22端口,为了增强安全性或满足特定需求,可以通过修改SSH配置来增加或更改SSH访问端口,具体步骤包括修改SSH配置文件、增加或修改... 目录1. 修改 SSH 配置文件2. 增加或修改端口3. 保存并退出编辑器4. 更新防火墙规则使用uf