shell之grep操作

GREP

grep(Global search Regular Expression and Print out the line)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

grep 例子

  1. grep 'word' filename: 搜索文件中包含word的行;
  2. grep -i 'bar' file1:在文件中不区分大小写搜索bar;
  3. grep -R foo: 在当前文件夹及其子文件下搜索单词foo;
  4. grep -c 'nixcraft' frontpage.md: 在frontpage.md文件中搜索并显示'nixcraftq'出现的次数;

在linux和unix中的语法

grep 'word' filename
grep 'word' file1 file2 file3
grep 'string1 string2'  filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName

使用grep在linux文件中搜索

在/etc/passwd文件中搜索boo:

grep boo /etc/passwd

不区分大小写的搜索boo,Boo和BOO等:

grep -i "boo" /etc/passwd

最后grep命令可以接在cat之后:

cat /etc/passwd | grep -i "boo"

迭代使用

-R或-r参数可以在文件夹和子文件夹下迭代查找

grep -r "192.168.1.5" /etc/

返回为

/etc/ppp/options:# ms-wins 192.168.1.50
/etc/ppp/options:# ms-wins 192.168.1.51

-h参数可以略去文件名,-n参数可以显示行号:

仅搜索单个单词

当使用grep搜索boo时,返回的可能有fooboo,boo123等。-w参数可以仅搜索一个boo单词:

grep -w "boo" file

搜索两个不同的单词

使用egrep命名:

egrep -w 'word1|word2' file

显示文件中被匹配的行数

使用-c参数,grep可以报告每个文件中匹配的行数

grep -c 'word' /path/to/file

显示未匹配

使用-v参数可以打印未匹配的行:

grep -v 'bar' /path/to/file

linux管道和grep

grep参数可以用在pipes中,使用|命令。
例如打印cpu模式

cat /proc/cpuinfo | grep -i 'Model'

可以结合apt search寻找安装包

列出匹配成功的文件名

使用-l命令列出包含main()的文件名:

grep -l 'main' *.c

总结

参数 描述
-i 忽略大小写
-n 仅匹配整个单词
-v 选择未匹配模式
-n 打印行号
-h 不显示文件名
-r 迭代进行
-R 迭代进行
-l 仅打印匹配成功的文件名
-c 仅打印文件中匹配成功的行数
--color 使用彩色显示成功匹配

猜你喜欢

转载自www.cnblogs.com/zi-wang/p/12332058.html