一天一个 Linux 命令(19):grep 命令

本文为joshua317原创文章,转载请注明:转载自joshua317博客 一天一个 Linux 命令(19):grep 命令 - joshua317的博客

一、简介

Linux系统里的grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。grep全称是Global Regular Expression Print,表示全局正则表达式版本,它的使用权限是所有用户。

grep 指令用于查找内容包含指定的字符的文件,如果发现某文件的内容符合所指定的字符,预设 grep 指令会把含有字符的那一列显示出来。若不指定任何文件名称,或是所给予的文件名为 -,则 grep 指令会从标准输入设备读取数据。

grep的工作方式是这样的,它在一个或多个文件中搜索字符串模板。如果模板包括空格,则必须被引用,模板后的所有字符串被看作文件名。搜索的结果被送到标准输出,不影响原文件内容。

grep在shell脚本的使用中,grep通过返回一个状态值来说明搜索的状态,如果模板搜索成功,则返回0,如果搜索不成功,则返回1,如果搜索的文件不存在,则返回2。我们利用这些返回值就可进行一些自动化的文本处理工作。

作为linux中最为常用的三大文本(awk,sed,grep)处理工具之一,掌握好其用法是很有必要的。

二、格式说明

grep [OPTION]... PATTERN [FILE]...


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.c

Regexp 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 newline

Miscellaneous:
  -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 exit

Output 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-recursive
                            likewise, but follow all symlinks
      --include=FILE_PATTERN
                            search only files that match FILE_PATTERN
      --exclude=FILE_PATTERN
                            skip 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 name

Context 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.

三、选项说明

-a,--text : 不忽略二进制的数据。
-A<显示行数>,--after-context=<显示行数> : 除了显示符合字符的那一行之外,并显示该行之后的内容。
-b,--byte-offset : 在显示符合字符的那一行之前,标示出该行第一个字符的编号。
-B<显示行数> ,--before-context=<显示行数> : 除了显示符合字符的那一行之外,并显示该行之前的内容。
-c, --count : 计算符合字符的列数。
-C<显示行数>, --context=<显示行数>或-<显示行数> : 除了显示符合字符的那一行之外,并显示该行之前后的内容。
-d <动作>, --directories=<动作> : 当指定要查找的是目录而非文件时,必须使用这项参数,否则grep指令将回报信息并停止动作。
-e<字符>, --regexp=<字符> : 指定字符串做为查找文件内容的字符。
-E, --extended-regexp : 将字符为延伸的正则表达式来使用。
-f<规则文件>, --file=<规则文件> : 指定规则文件,其内容含有一个或多个规则字符,让grep查找符合规则条件的文件内容,格式为每行一个规则字符。
-F, --fixed-regexp : 将字符视为固定字符串的列表。
-G, --basic-regexp : 将字符视为普通的表示法来使用。
-h, --no-filename : 在显示符合字符的那一行之前,不标示该行所属的文件名称。
-H, --with-filename : 在显示符合字符的那一行之前,表示该行所属的文件名称。
-i, --ignore-case : 忽略字符大小写的差别。
-l, --file-with-matches : 列出文件内容符合指定的字符的文件名称。
-L, --files-without-match : 列出文件内容不符合指定的字符的文件名称。
-n, --line-number : 在显示符合字符的那一行之前,标示出该行的列数编号。
-o, --only-matching : 只显示匹配PATTERN 部分。
-q, --quiet或--silent : 不显示任何信息。
-r, --recursive : 此参数的效果和指定"-d recurse"参数相同。
-s, --no-messages : 不显示错误信息。
-v, --invert-match : 显示不包含匹配文本的所有行。
-V, --version : 显示版本信息。
-w, --word-regexp : 只显示全字符合的列。
-x, --line-regexp : 只显示全列符合的列。
-y : 此参数的效果和指定"-i"参数相同。

四、命令功能

用于过滤/搜索的特定字符。也可使用正则表达式,多种命令配合使用,使用上更加灵活。

五、常见用法

1.在文件中查找要搜索的字符

grep joshua317 test.txt

2.在多个文件中查找关键词

grep joshua317 test.txt test2.txt

#result:
# grep joshua317 test.txt test2.txt
test.txt:joshua317
test.txt:joshua317
grep: test2.txt: No such file or directory

3.在文件中查找要搜索的字符,并显示行数

grep -n joshua317 test.txt

#result:
# grep -n joshua317 test.txt
2:joshua317
7:joshua317

4.反向查找。上面的例子是查找并打印出符合条件的行,通过"-v"参数可以打印出不符合条件行的内容。

grep -v joshua317 test.txt 

#result:
# grep -v joshua317 test.txt 
hello
i
love
China
,
my
name
yes

5.查找时不区分大小写

grep –i "joshua317" test.txt 

6.查找后缀有txt字样的文件中包含 joshua317字符串的文件

grep -l joshua317 *txt

#result:
# grep -l joshua317 *txt
test.txt

7.以递归的方式查找符合条件的文件

grep -r joshua317 /root/test

#result:
# grep -r joshua317 test
test/tree.txt:joshua317
test/test.txt:joshua317
test/test2/test.txt:joshua317

8.管道符使用,查找指定进程

ps -ef|grep java

9.管道符使用,grep不显示本身进程

ps aux | grep java | grep -v "grep"

10.管道符使用,查找指定进程个数

ps -ef|grep -c java

11.从文件中读取关键词进行搜索,输出一个文件中含有从另外一个文件中读取出的关键词的内容行

cat test.txt | grep -f joshua317

12.从当前目录开始查找所有扩展名为 .txt 的文本文件,并找出包含 "joshua317" 的行

find ./ -name "*.txt" | xargs grep "joshua317"

13.从根目录开始查找所有扩展名为 .log 的文本文件,并找出包含 "ERROR" 的行:

find / -type f -name "*.log" | xargs grep "ERROR"

14.从文件内容查找与正则表达式匹配的行

grep –e "正则表达式" 文件名

15.查找以j开头的行内容

cat test.txt |grep ^j

#result:
# cat test.txt |grep ^j
joshua317
joshua317

16.查找非u开头的行内容

cat test.txt |grep ^[^j]

#result:
# cat test.txt |grep ^[^j]
hello
i
love
China
,
my
name
yes

17.查找以na结尾的行内容

cat test.txt |grep na$

#result:
# cat test.txt |grep na$
China

18.显示包含ove或者shua字符的内容行

cat test.txt |grep -E "ove|shua"

#result:
# cat test.txt |grep -E "ove|shua"
joshua317
love
joshua317

19.查找当前目录下面以.txt 结尾的文件中的所有包含每个字符串至少有3个连续小写字符的字符串的行

grep '[a-z]\{3\}' *.txt

#result:
# grep '[a-z]\{3\}' *.txt
test2.txt:ove
test2.txt:ina
test.txt:hello
test.txt:joshua317
test.txt:love
test.txt:China
test.txt:joshua317
test.txt:name
test.txt:yes

20.查找文件中字符串至少有3个数字的字符串的行

grep '[0-9]\{3\}' test.txt

#result:
# grep '[0-9]\{3\}' test.txt
joshua317
joshua317

本文为joshua317原创文章,转载请注明:转载自joshua317博客 一天一个 Linux 命令(19):grep 命令 - joshua317的博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值