Linux :: 内容过滤指令【3】:grep 指令【详解】:在指定文件中过滤搜索信息、(模糊)查找包含指定字符串的内容!(如:系统故障时,查看操作日志信息等情景)

前言:本篇是 Linux 基本操作篇章的内容!
笔者使用的环境是基于腾讯云服务器:CentOS 7.6 64bit。


学习集:

  • C++ 入门到入土!!!学习合集
  • Linux 从命令到网络再到内核!学习合集

注:find 指令常与 grep 指令在面试中被提及,需让你回答异同!


目录索引:
1. 基本语法、功能及使用方式
2. 基本用法示例:过滤查找内容
3.「-v」:反向过滤掉指定内容输出
4. 其他简单可选参数
4.1 「-i」:不区分大小写过滤查找
4.2 「-j」:顺带输出行号
5. 补充说明:关联正则表达式
6. 相关文章或系列推荐


1. 基本语法、功能及使用方式

1.1 基本语法

基本语法: grep [option] 搜寻字符串 文件

1.2 功能及使用方式

功能:在文件中搜索字符串,将找到的行打印出来


使用方式(两种):

  • grep 指定字符串 指定文件
  • cat 指定文件 | grep 指定字符串【该方式结合管道使用!】
    (使用方式见本文的第二点)

2. 基本用法示例:过滤查找内容

测试用例生成

/* 拷贝数据集文件用于测试,注:若无该文件集可使用如下指令生成:
	count=0; while [ $count -le 100 ]; do echo "hello ${count}"; let count++; done > file.txt
*/
[Mortal@VM-12-16-centos test_findsome]$ cd ~
[Mortal@VM-12-16-centos ~]$ ls
StudyingOrder_Linux  test1  test2  test3  test_cp  test_findsome  test_mkdir  test_mv  test_txtfile
[Mortal@VM-12-16-centos ~]$ ls test_txtfile
file.txt  filetxt.txt  main.c
[Mortal@VM-12-16-centos ~]$ cp test_txtfile/file.txt test_findsome/grep_test.txt
[Mortal@VM-12-16-centos ~]$ cd test_findsome/

过滤查找内容:即(模糊)查找包含指定字符串的内容!

/* 方式一:grep 指定字符串 指定文件 */
[Mortal@VM-12-16-centos test_findsome]$ grep "0" grep_test.txt 
hello 0
hello 10
hello 20
hello 30
hello 40
hello 50
hello 60
hello 70
hello 80
hello 90
hello 100

/* 方式二:cat 指定文件 | grep 指定字符串【该方式结合管道使用!】 */
[Mortal@VM-12-16-centos test_findsome]$ cat grep_test.txt | grep "0"
hello 0
hello 10
hello 20
hello 30
hello 40
hello 50
hello 60
hello 70
hello 80
hello 90
hello 100

3. 「-v」:反向过滤掉指定内容输出

-v:是一个可选项,作用:反向选择,亦即显示出没有 ‘搜寻字符串’ 内容的那一行

/* 方式一:grep 指定字符串 指定文件 */
[Mortal@VM-12-16-centos test_findsome]$ grep -v "0" grep_test.txt 
hello 1
hello 2
hello 3
hello 4
hello 5
hello 6
hello 7
.../* 数据过多,省略不复制出来 */

/* 方式二:cat 指定文件 | grep 指定字符串【该方式结合管道使用!】 */
[Mortal@VM-12-16-centos test_findsome]$ cat grep_test.txt | grep -v "0"
hello 1
hello 2
hello 3
hello 4
hello 5
hello 6
hello 7
.../* 数据过多,省略不复制出来 */

4. 其他简单可选参数

4.1 「-i」:不区分大小写过滤查找

  • grep -i 指定字符串 指定文件
  • cat 指定文件 | grep -i 指定字符串【该方式结合管道使用!】

4.2 「-j」:顺带输出行号

  • grep -n 指定字符串 指定文件
  • cat 指定文件 | grep -n 指定字符串【该方式结合管道使用!】

5. 补充说明:关联正则表达式

此时,只是简单先介绍以上内容!后续会持续更新本文!

说明:grep 指令现在也支持通配符/正则表达式等!

例如:cat grep_test.txt | grep -v “hello 9[0-5]”

[Mortal@VM-12-16-centos test_findsome]$ cat grep_test.txt | grep 'hello 9[0-5]'
hello 90
hello 91
hello 92
hello 93
hello 94
hello 95

6. 相关文章或系列推荐

1. Linux 学习目录合集 ;


2. Linux :: 【基础指令篇 :: 查找 / 查询指令:(1)】:: which 指令 :指定系统文件(指令)查找指令 | 查询指令的别名
3. Linux :: 文件查找指令【2】:find 指令(重点):用于在文件树中查找文件(指定路径/目录),并作出相应的处理(可能访问磁盘)【随知识体系持续更新】


你可能感兴趣的:(Linux,学习,linux,服务器,学习,笔记)