
Linux 中的 grep(global regular expression)命令主要用于在文件中查找符合特定条件的字符串或正则表达式内容。
该命令可用于搜索包含指定模板样式的文件内容,若某文件中存在匹配的样式,默认情况下 grep 会输出该行内容。如果不指定具体文件名,或者文件名为“-”,则命令将从标准输入读取数据。
<pre class="brush:php;toolbar:false;">grep [options] pattern [files] 或 grep [-abcEFGhHilLnqrsvVwxy][-A][-B][-C][-d][-e][-f][--help][范本样式][文件或目录...]
常用选项说明:
-i
-v
-n
-r
-l
-c
更多参数说明:
-i
1、在 file.txt 文件中查找 "hello" 字符串,并输出匹配的行:
<pre class="brush:php;toolbar:false;">grep hello file.txt
2、递归查找 dir 目录下所有文件中符合 "pattern" 的内容,并显示文件名和行号:
<pre class="brush:php;toolbar:false;">grep -r -n pattern dir/
3、从标准输入中查找 "world",并仅输出匹配行的数量:
<pre class="brush:php;toolbar:false;">echo "hello world" | grep -c world
4、在当前目录中查找后缀为 file 的文件中是否包含 test 字符串,并输出相关行:
<pre class="brush:php;toolbar:false;">grep test *file
执行结果如下:
<pre class="brush:php;toolbar:false;">$ grep test test* testfile1:This a Linux testfile! testfile_2:This is a linux testfile! testfile_2:Linux test
5、递归查找 /etc/acpi 目录下的所有文件中是否包含 "update",并输出匹配行内容:
<pre class="brush:php;toolbar:false;">grep -r update /etc/acpi
输出示例:
<pre class="brush:php;toolbar:false;">$ grep -r update /etc/acpi /etc/acpi/ac.d/85-anacron.sh:# (Things like the slocate updatedb cause a lot of IO.) Rather than /etc/acpi/resume.d/85-anacron.sh:# (Things like the slocate updatedb cause a lot of IO.) Rather than /etc/acpi/events/thinkpad-cmos:action=/usr/sbin/thinkpad-keys--update
6、反向查找:查找文件名含 test 的文件中不含 test 的行:
<pre class="brush:php;toolbar:false;">grep -v test *test*
输出如下:
<pre class="brush:php;toolbar:false;">$ grep-v test* testfile1:helLinux! testfile1:Linis a free Unix-type operating system. testfile1:Lin testfile_1:HELLO LINUX! testfile_1:LINUX IS A FREE UNIX-TYPE OPTERATING SYSTEM. testfile_1:THIS IS A LINUX TESTFILE! testfile_2:HELLO LINUX! testfile_2:Linux is a free unix-type opterating system.
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号