my_study_grep’s 学习笔记¶
文本处理三剑客¶
01 简介¶
grep在输入文件中搜索包含匹配给定模式列表的行。 当它在一行中找到匹配项时,它将该行复制到标准输出(默认情况下),或者产生您请求的任何其他类型的输出。
虽然grep希望对文本进行匹配,但除了可用内存之外,对输入行长度没有限制,并且可以匹配一行内的任意字符。 如果输入文件的最后一个字节不是换行符,那么grep默默提供一个。 由于换行符也是模式列表的分隔符,因此无法在文本中匹配换行符。
02 调用grep¶
调用grep的用法:
grep options pattern input_file_names
2.1 命令行选项¶
--help | 获取帮助 |
-V | 获取版本 |
--version | 获取版本 |
-e | 指定模式,可以多次使用 |
--regexp | 指定模式,可以多次使用 |
-f | 模式从文件来 |
-file | 模式从文件来 |
-i | 忽略大小写 |
-y | 忽略大小写 |
--ignore-case | 忽略大小写 |
-v | 反向匹配 |
--invert-match | 反向匹配 |
-w | 单词匹配 |
--word-regexp | 单词匹配 |
-x | 整行匹配 |
--line-regexp | 整行匹配 |
-c | 显示匹配的个数 |
--count | 显示匹配的个数 |
--color | 给匹配到的结果上色 |
-m | 最大的匹配个数 |
--max-count | 最大的匹配个数 |
-o | 只显示匹配的行 |
--only-matching | |
只显示匹配的行 | |
-q | 静默模式 |
--quiet | 静默模式 |
--silent | 静默模式 |
-b | 显示偏移字节数 |
--btype-offset | 显示偏移字节数 |
-H | 显示文件名 |
--with-filename | |
显示文件名 | |
-n | 显示行号 |
--line-number | 显示行号 |
-A | 匹配行后面几行显示 |
--after-content | |
匹配行后面几行显示 | |
-B | 匹配行前面几行显示 |
--before-context | |
匹配行前面几行显示 | |
-C | 匹配前后几行显示 |
--context | 匹配行前后几行显示 |
-d | 如果输入文件是目录,使用指定的action去处理,有read,skip,recurse, |
--directories | 如果输入文件是目录,使用指定的action去处理,有read,skip,recurse, |
-r | 输入文件是目录,递归 |
--recursive | 输入文件是目录,递归 |
-R | 递归,且追踪符号链接 |
2.2 环境变量¶
grep是受到一些环境变量影响的。
04 使用grep¶
4.1 列出匹配的文件中那个有指定的字符串¶
[root@centos74 test]$ grep -l 'main' *.txt lines.txt
*.txt 代表目录下的所有txt文件。 找这些文件中的包含main的。显示出来的是文件名
4.3 如果模式中有前导-¶
grep -e '--cut here--' *
4.4 搜索整个单词而不是单词的一部分¶
grep -w 'hello' *
4.6 强制grep打印文件名¶
[root@centos74 test]$ grep -H 'root' /etc/passwd
/etc/passwd:root:x:0:0:root:/root:/bin/bash
/etc/passwd:operator:x:11:0:operator:/root:/sbin/nologin
/etc/passwd:dockerroot:x:606:606:Docker User:/var/lib/docker:/sbin/nologin
[root@centos74 test]$ grep 'root' /etc/passwd /dev/null
/etc/passwd:root:x:0:0:root:/root:/bin/bash
/etc/passwd:operator:x:11:0:operator:/root:/sbin/nologin
/etc/passwd:dockerroot:x:606:606:Docker User:/var/lib/docker:/sbin/nologin
4.7 接受重定向的输入¶
[root@centos74 test]$ ps aux |grep httpd
root 1113 0.0 0.2 221952 4980 ? Ss 11:19 0:02 /usr/sbin/httpd -DFOREGROUND
apache 1296 0.0 0.1 224036 3104 ? S 11:20 0:00 /usr/sbin/httpd -DFOREGROUND
apache 1297 0.0 0.1 224036 3104 ? S 11:20 0:00 /usr/sbin/httpd -DFOREGROUND
apache 1298 0.0 0.1 224036 3104 ? S 11:20 0:00 /usr/sbin/httpd -DFOREGROUND
apache 1299 0.0 0.1 224036 3104 ? S 11:20 0:00 /usr/sbin/httpd -DFOREGROUND
apache 1300 0.0 0.1 224036 3104 ? S 11:20 0:00 /usr/sbin/httpd -DFOREGROUND
root 12232 0.0 0.0 112664 960 pts/1 S+ 21:00 0:00 grep --color httpd
4.8 grep 多次¶
grep 'paul' /etc/motd | grep 'franc,ois'
\ Sort by:\ best rated\ newest\ oldest\
\\
Add a comment\ (markup):
\``code``
, \ code blocks:::
and an indented block after blank line