linux-文本处理-grep

grep

官方文档:https://man7.org/linux/man-pages/man1/grep.1.html

如果安装了完整版的man手册,使用info man查看详细的手册

示例使用的文本

cat greptxt.txt
whole word
word
abcword
abc abc word abc
wordabc asd
abc abc abcword
word*abc asd
word*
123

-e

指定多个匹配模式

image-20210713094501518

匹配行中带有123或者word的行,grep*表示当前文件夹下文件名以grep开头的文件

支持“basic” (BRE),“extended” (ERE) 和“perl” (PCRE)多个版本的正则表达式,如中括号[]问号?星号*点.加号+大括号{}

引号

当所匹配的字符包含空格可以使用引号,单引号或双引号都可以

 grep -e "whole word" grep*
 greptxt.txt:whole word

-f

执行正则匹配文件

-i

忽略大小写:ignore case

cat greptxt2.txt
abc 1234
aBC 123
Abc
grep -i abc greptxt2.txt
abc 1234
aBC 123
Abc
grep abc greptxt2.txt
abc 1234

grep默认不略大小写,对应的命令是 --no-ignore-case-i则忽略大小写

-v

反向匹配:invert match

grep -v word greptxt.txt
123

匹配找不到指定单词的行

-w

单词正则表达式:word regexp

grep -w word greptxt.txt
whole word
word
abc abc word abc
word*abc asd
word*

匹配完整的单词,单词理解为:行首、行尾或行中,前后都不是单词字符(即字符、数字、下划线),所以示例中*号也可以选出来

-c

计算匹配的总数

grep -c word greptxt.txt
8
# 计算多个文件匹配的总数
grep -c word grep*
greptxt.txt:8
greptxt2.txt:0

返回匹配的总数,而不直接数据行内容

-l或-L

grep -L word grep*
greptxt2.txt
grep -l word grep*
greptxt.txt

-l:返回匹配到指定字符的文件名称

-L:返回没有匹配到指定字符的文件名称

-m

指定匹配的最大数量:max count

grep -m 2 word greptxt.txt
whole word
word

这里greptxt.txt原来能匹配到8行,指定max count为2后匹配到2行就退出

-o

只返回匹配的部分:only matching

grep -o w.*d greptxt.txt
whole word
word
word
word
wordabc asd
word
word*abc asd
word

这里使用.*表示匹配任意字符串,返回符合w.*d的字符串

-b

文件偏移量:byte offset

grep -b w.*d greptxt.txt
0:whole word
12:word
18:abcword
27:abc abc word abc
45:wordabc asd
58:abc abc abcword
75:word*abc asd
89:word*

grep -o -b w.*d greptxt.txt
0:whole word
12:word
21:word
35:word
45:wordabc asd
69:word
75:word*abc asd
89:word

匹配到行时,先返回匹配到的所在行在文件中的偏移量

如果指定-o, 则数据匹配到的字符的偏移量

-H

输出文件名:with filename

grep -H abc greptxt.txt
greptxt.txt:abcword
greptxt.txt:abc abc word abc
greptxt.txt:wordabc asd
greptxt.txt:abc abc abcword
greptxt.txt:word*abc asd

如果有多个文件,-H默认启用

-n

输出行号:line number

grep -n -e 'word' greptxt.txt
1:whole word
2:word
3:abcword
4:abc abc word abc
5:wordabc asd
6:abc abc abcword
7:word*abc asd
8:word*

输出匹配到的行内容时,先输入行号

-s

默认情况下,当遇到不可读或者不存在的文件时,会输出相应的提示,如果加了-s 则不会打印相应的信息

-r

递归遍历所有目录以及子目录下的文件

grep -n -e 'word' ../*
grep: ../antSword-master: Is a directory
grep: ../conf.d: Is a directory
grep: ../grep: Is a directory
Binary file ../nox_setup_v7.0.1.0_full_intl.exe matches
../页面路径数据.sql:17:(5, '忘记密码-修改', '/login/change-password'),
../页面路径数据.sql:18:(6, '忘记密码-发邮件', '/login/forgot-password'),

grep -n -s -e 'word' ../*
Binary file ../nox_setup_v7.0.1.0_full_intl.exe matches
../页面路径数据.sql:17:(5, '忘记密码-修改', '/login/change-password'),
../页面路径数据.sql:18:(6, '忘记密码-发邮件', '/login/forgot-password'),

grep -n -r -e 'word' ../*
# 数据太多不展示

../*匹配上级目录下所有文件,默认情况不访问文件夹

-R

递归遍历所有目录,包括符合链接symbolic links

原文地址:https://www.cnblogs.com/froggengo/p/15008819.html