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内核参数配置与验证详细指南》在Linux系统运维和性能优化中,内核参数(sysctl)的配置至关重要,本文主要来聊聊如何配置与验证这些Linux内核参数,希望对大家有一定的帮助... 目录1. 引言2. 内核参数的作用3. 如何设置内核参数3.1 临时设置(重启失效)3.2 永久设置(重启仍生效

基于Java实现回调监听工具类

《基于Java实现回调监听工具类》这篇文章主要为大家详细介绍了如何基于Java实现一个回调监听工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录监听接口类 Listenable实际用法打印结果首先,会用到 函数式接口 Consumer, 通过这个可以解耦回调方法,下面先写一个

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

JS+HTML实现在线图片水印添加工具

《JS+HTML实现在线图片水印添加工具》在社交媒体和内容创作日益频繁的今天,如何保护原创内容、展示品牌身份成了一个不得不面对的问题,本文将实现一个完全基于HTML+CSS构建的现代化图片水印在线工具... 目录概述功能亮点使用方法技术解析延伸思考运行效果项目源码下载总结概述在社交媒体和内容创作日益频繁的

kali linux 无法登录root的问题及解决方法

《kalilinux无法登录root的问题及解决方法》:本文主要介绍kalilinux无法登录root的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录kali linux 无法登录root1、问题描述1.1、本地登录root1.2、ssh远程登录root2、

C#TextBox设置提示文本方式(SetHintText)

《C#TextBox设置提示文本方式(SetHintText)》:本文主要介绍C#TextBox设置提示文本方式(SetHintText),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录C#TextBox设置提示文本效果展示核心代码总结C#TextBox设置提示文本效果展示核心代

基于Python打造一个全能文本处理工具

《基于Python打造一个全能文本处理工具》:本文主要介绍一个基于Python+Tkinter开发的全功能本地化文本处理工具,它不仅具备基础的格式转换功能,更集成了中文特色处理等实用功能,有需要的... 目录1. 概述:当文本处理遇上python图形界面2. 功能全景图:六大核心模块解析3.运行效果4. 相

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

Linux ls命令操作详解

《Linuxls命令操作详解》通过ls命令,我们可以查看指定目录下的文件和子目录,并结合不同的选项获取详细的文件信息,如权限、大小、修改时间等,:本文主要介绍Linuxls命令详解,需要的朋友可... 目录1. 命令简介2. 命令的基本语法和用法2.1 语法格式2.2 使用示例2.2.1 列出当前目录下的文

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效