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 rm命令误操作的多场景防护方案与实践

《防止Linuxrm命令误操作的多场景防护方案与实践》在Linux系统中,rm命令是删除文件和目录的高效工具,但一旦误操作,如执行rm-rf/或rm-rf/*,极易导致系统数据灾难,本文针对不同场景... 目录引言理解 rm 命令及误操作风险rm 命令基础常见误操作案例防护方案使用 rm编程 别名及安全删除

Linux下MySQL数据库定时备份脚本与Crontab配置教学

《Linux下MySQL数据库定时备份脚本与Crontab配置教学》在生产环境中,数据库是核心资产之一,定期备份数据库可以有效防止意外数据丢失,本文将分享一份MySQL定时备份脚本,并讲解如何通过cr... 目录备份脚本详解脚本功能说明授权与可执行权限使用 Crontab 定时执行编辑 Crontab添加定

Java实现在Word文档中添加文本水印和图片水印的操作指南

《Java实现在Word文档中添加文本水印和图片水印的操作指南》在当今数字时代,文档的自动化处理与安全防护变得尤为重要,无论是为了保护版权、推广品牌,还是为了在文档中加入特定的标识,为Word文档添加... 目录引言Spire.Doc for Java:高效Word文档处理的利器代码实战:使用Java为Wo

使用docker搭建嵌入式Linux开发环境

《使用docker搭建嵌入式Linux开发环境》本文主要介绍了使用docker搭建嵌入式Linux开发环境,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录1、前言2、安装docker3、编写容器管理脚本4、创建容器1、前言在日常开发全志、rk等不同

Python实战之SEO优化自动化工具开发指南

《Python实战之SEO优化自动化工具开发指南》在数字化营销时代,搜索引擎优化(SEO)已成为网站获取流量的重要手段,本文将带您使用Python开发一套完整的SEO自动化工具,需要的可以了解下... 目录前言项目概述技术栈选择核心模块实现1. 关键词研究模块2. 网站技术seo检测模块3. 内容优化分析模

linux系统上安装JDK8全过程

《linux系统上安装JDK8全过程》文章介绍安装JDK的必要性及Linux下JDK8的安装步骤,包括卸载旧版本、下载解压、配置环境变量等,强调开发需JDK,运行可选JRE,现JDK已集成JRE... 目录为什么要安装jdk?1.查看linux系统是否有自带的jdk:2.下载jdk压缩包2.解压3.配置环境

Linux搭建ftp服务器的步骤

《Linux搭建ftp服务器的步骤》本文给大家分享Linux搭建ftp服务器的步骤,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录ftp搭建1:下载vsftpd工具2:下载客户端工具3:进入配置文件目录vsftpd.conf配置文件4:

Linux实现查看某一端口是否开放

《Linux实现查看某一端口是否开放》文章介绍了三种检查端口6379是否开放的方法:通过lsof查看进程占用,用netstat区分TCP/UDP监听状态,以及用telnet测试远程连接可达性... 目录1、使用lsof 命令来查看端口是否开放2、使用netstat 命令来查看端口是否开放3、使用telnet

Linux系统管理与进程任务管理方式

《Linux系统管理与进程任务管理方式》本文系统讲解Linux管理核心技能,涵盖引导流程、服务控制(Systemd与GRUB2)、进程管理(前台/后台运行、工具使用)、计划任务(at/cron)及常用... 目录引言一、linux系统引导过程与服务控制1.1 系统引导的五个关键阶段1.2 GRUB2的进化优

Python文本相似度计算的方法大全

《Python文本相似度计算的方法大全》文本相似度是指两个文本在内容、结构或语义上的相近程度,通常用0到1之间的数值表示,0表示完全不同,1表示完全相同,本文将深入解析多种文本相似度计算方法,帮助您选... 目录前言什么是文本相似度?1. Levenshtein 距离(编辑距离)核心公式实现示例2. Jac