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

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


学习集:


注: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 指令(重点):用于在文件树中查找文件(指定路径/目录),并作出相应的处理(可能访问磁盘)【随知识体系持续更新】


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NPC的白话文谈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值