grep命令

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

语法

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

参数

示例

hello.c文件内容如下:

#include <stdio.h>
#include <stdlib.h>

int main() {
   printf("Hello World\n");
   printf("Hello World\n");
   printf("Hello World\n");
   return 0;
}

匹配带有Hello的行。

grep Hello hello.c
#    printf("Hello World\n");
#    printf("Hello World\n");
#    printf("Hello World\n");

匹配带有Hello行的数量。

grep -c Hello hello.c
# 3

反转匹配的意义,选择不匹配Hello的行。

grep -v Hello hello.c
# #include <stdio.h>
# #include <stdlib.h>
#
# int main() {
#    return 0;
# }

匹配带有i的行并忽略大小写。

grep -i I hello.c
# #include <stdio.h>
# #include <stdlib.h>
# int main() {
#    printf("Hello World\n");
#    printf("Hello World\n");
#    printf("Hello World\n");

仅输出与文件整行匹配的行。

grep -x "   return 0;" hello.c
#    return 0;

匹配带有Hello的行并输出行号。

grep -n Hello hello.c
# 5:   printf("Hello World\n");
# 6:   printf("Hello World\n");
# 7:   printf("Hello World\n");

递归匹配当前目录下所有文件中能够匹配h*的文件,输出行号并忽略大小写,注意实际在终端中匹配成功的位置会使用红色字体标注。

grep -rni "h*" ./
# ./hello.c:1:#include <stdio.h>
# ./hello.c:2:#include <stdlib.h>
# ./hello.c:3:
# ./hello.c:4:int main() {
# ./hello.c:5:   printf("Hello World\n");
# ./hello.c:6:   printf("Hello World\n");
# ./hello.c:7:   printf("Hello World\n");
# ./hello.c:8:   return 0;
# ./hello.c:9:}

参考

https://www.runoob.com/linux/linux-comm-grep.html
https://www.tutorialspoint.com/unix_commands/grep.htm
https://www.geeksforgeeks.org/fold-command-in-linux-with-examples/