Linux系统文本三剑客之grep使用方法

简介: Linux系统文本三剑客之grep使用方法

一、grep介绍

Linux grep 命令用于查找文件里符合条件的字符串。

二、grep的常用选项

-a 或 --text : 不要忽略二进制的数据。
-A<显示行数> 或 --after-context=<显示行数> : 除了显示符合范本样式的那一列之外,并显示该行之后的内容。
-b 或 --byte-offset : 在显示符合样式的那一行之前,标示出该行第一个字符的编号。
-B<显示行数> 或 --before-context=<显示行数> : 除了显示符合样式的那一行之外,并显示该行之前的内容。
-c 或 --count : 计算符合样式的列数。
-C<显示行数> 或 --context=<显示行数>或-<显示行数> : 除了显示符合样式的那一行之外,并显示该行之前后的内容。
-d <动作> 或 --directories=<动作> : 当指定要查找的是目录而非文件时,必须使用这项参数,否则grep指令将回报信息并停止动作。
-e<范本样式> 或 --regexp=<范本样式> : 指定字符串做为查找文件内容的样式。
-E 或 --extended-regexp : 将样式为延伸的正则表达式来使用。
-f<规则文件> 或 --file=<规则文件> : 指定规则文件,其内容含有一个或多个规则样式,让grep查找符合规则条件的文件内容,格式为每行一个规则样式。
-F 或 --fixed-regexp : 将样式视为固定字符串的列表。
-G 或 --basic-regexp : 将样式视为普通的表示法来使用。
-h 或 --no-filename : 在显示符合样式的那一行之前,不标示该行所属的文件名称。
-H 或 --with-filename : 在显示符合样式的那一行之前,表示该行所属的文件名称。
-i 或 --ignore-case : 忽略字符大小写的差别。
-l 或 --file-with-matches : 列出文件内容符合指定的样式的文件名称。
-L 或 --files-without-match : 列出文件内容不符合指定的样式的文件名称。
-n 或 --line-number : 在显示符合样式的那一行之前,标示出该行的列数编号。
-o 或 --only-matching : 只显示匹配PATTERN 部分。
-q 或 --quiet或--silent : 不显示任何信息。
-r 或 --recursive : 此参数的效果和指定"-d recurse"参数相同。
-s 或 --no-messages : 不显示错误信息。
-v 或 --invert-match : 显示不包含匹配文本的所有行。
-V 或 --version : 显示版本信息。
-w 或 --word-regexp : 只显示全字符合的列。
-x --line-regexp : 只显示全列符合的列。
-y : 此参数的效果和指定"-i"参数相同。

三、grep的日常用法

1.过滤目录下以.conf结尾的文件中含root的文件

[root@server-01 ~]# grep root /etc/*.conf
/etc/kdump.conf:# no effect once the root filesystem is mounted and the normal init scripts are
/etc/kdump.conf:#             via ssh. The default value is /root/.ssh/kdump_id_rsa.
/etc/kdump.conf:#             case, "path" represents the absolute path from root. The
/etc/kdump.conf:# failure_action <reboot | halt | poweroff | shell | dump_to_rootfs>
/etc/kdump.conf:#             dump_to_rootfs:  Dump vmcore to rootfs from initramfs context and
/etc/kdump.conf:#                       Useful when non-root dump target is specified.
/etc/kdump.conf:# default <reboot | halt | poweroff | shell | dump_to_rootfs>
/etc/kdump.conf:#             when "shell" or "dump_to_rootfs" failure action finishes.
/etc/kdump.conf:#sshkey /root/.ssh/kdump_id_rsa
/etc/oddjobd.conf:         <allow user="root"/>
/etc/oddjobd.conf:          <allow user="root"/>
/etc/oddjobd.conf:          <allow user="root"/>
/etc/xattr.conf:xfsroot.*            skip        # xfs specific; obsolete

2.查找目录下所有文件包含koel的文件

[root@server-01 ~]# grep -r koel  /var/log/
/var/log/messages:May 17 02:55:51 server-01 dockerd[1199]: time="2022-05-17T02:55:51.227750394+08:00" level=info msg="Removing stale endpoint music_koel_1 (fe6e89c49e41cb4e8bb7861b5c334bb0701ccb4f3d1d5122d12ebe449410b665)"
/var/log/messages:May 17 03:19:11 server-01 dockerd[1199]: time="2022-05-17T03:19:11.152928661+08:00" level=error msg="Handler for POST /v1.30/containers/9376dc41cd026582e66f83165cf9e5bc3be491d37ed1639afbb47f077a7e93de/start returned error: driver failed programming external connectivity on endpoint music_koel_1 (844b48c77c6be4bb615eaf4e92521c0ecc430990e9f5a1ceb607f2a6ae3b572c): Bind for 0.0.0.0:3006 failed: port is already allocated"
/var/log/messages:May 17 03:27:38 server-01 kernel: [12057]     0 12057     4492       75    81920        0             0 koel-entrypoint
/var/log/messages:May 17 03:29:17 server-01 kernel: [12057]     0 12057     4492       75    81920        0             0 koel-entrypoint
/var/log/messages:May 17 03:30:44 server-01 kernel: [12057]     0 12057     4492       75    81920        0             0 koel-entrypoint
/var/log/messages:May 17 03:31:46 server-01 kernel: [12057]     0 12057     4492       75    81920        0             0 koel-entrypoint
/var/log/messages:May 17 03:55:59 server-01 kernel: [23207]     0 23207     4492       76    77824        0             0 koel-entrypoint
/var/log/messages:May 17 15:26:04 server-01 kernel: [ 8733]     0  8733     4492       75    77824        0             0 koel-entrypoint

3.查找日志中特定时间内容

[root@server-01 ~]# grep -n '2022-05-17T08' /var/log/*.log
/var/log/dnf.librepo.log:275:2022-05-17T08:48:05Z INFO Librepo version: 1.12.0 with CURL_GLOBAL_ACK_EINTR support (libcurl/7.61.1 OpenSSL/1.1.1g zlib/1.2.11 brotli/1.0.6 libidn2/2.2.0 libpsl/0.20.2 (+libidn2/2.2.0) libssh/0.9.4/openssl/zlib nghttp2/1.33.0)
/var/log/dnf.librepo.log:276:2022-05-17T08:48:05Z INFO Librepo version: 1.12.0 with CURL_GLOBAL_ACK_EINTR support (libcurl/7.61.1 OpenSSL/1.1.1g zlib/1.2.11 brotli/1.0.6 libidn2/2.2.0 libpsl/0.20.2 (+libidn2/2.2.0) libssh/0.9.4/openssl/zlib nghttp2/1.33.0)
/var/log/dnf.log:926:2022-05-17T08:48:05Z INFO --- logging initialized ---
/var/log/dnf.log:927:2022-05-17T08:48:05Z DDEBUG timer: config: 36 ms
/var/log/dnf.log:928:2022-05-17T08:48:05Z DEBUG Loaded plugins: builddep, changelog, config-manager, copr, debug, debuginfo-install, download, generate_completion_cache, groups-manager, needs-restarting, playground, repoclosure, repodiff, repograph, repomanage, reposync
/var/log/dnf.log:929:2022-05-17T08:48:05Z DEBUG DNF version: 4.2.23
/var/log/dnf.log:930:2022-05-17T08:48:05Z DDEBUG Command: dnf makecache --timer 
/var/log/dnf.log:931:2022-05-17T08:48:05Z DDEBUG Installroot: /
/var/log/dnf.log:932:2022-05-17T08:48:05Z DDEBUG Releasever: 8
/var/log/dnf.log:933:2022-05-17T08:48:05Z DEBUG cachedir: /var/cache/dnf
/var/log/dnf.log:934:2022-05-17T08:48:05Z DDEBUG Base command: makecache
/var/log/dnf.log:935:2022-05-17T08:48:05Z DDEBUG Extra commands: ['makecache', '--timer']
/var/log/dnf.log:936:2022-05-17T08:48:05Z WARNING Repository extras is listed more than once in the configuration
/var/log/dnf.log:937:2022-05-17T08:48:05Z WARNING Repository PowerTools is listed more than once in the configuration
/var/log/dnf.log:938:2022-05-17T08:48:05Z WARNING Repository centosplus is listed more than once in the configuration
/var/log/dnf.log:939:2022-05-17T08:48:05Z DEBUG Making cache files for all metadata files.
/var/log/dnf.log:940:2022-05-17T08:48:05Z INFO Metadata cache refreshed recently.
/var/log/dnf.log:941:2022-05-17T08:48:05Z DDEBUG Cleaning up.
/var/log/dnf.rpm.log:4483:2022-05-17T08:48:05Z INFO --- logging initialized ---

4.过滤日志中err的信息

[root@server-01 ~]# find /var/log/ -type f -name "*.log" | xargs grep "ERROR"
/var/log/harbor/core.log:Dec 13 16:32:21 172.19.0.1 core[3330]: 2021-12-13T08:32:21Z [ERROR] [/common/config/manager.go:118]: loadSystemConfigFromEnv failed, config item, key: clair_db_port,  err: strconv.Atoi: parsing "": invalid syntax
/var/log/harbor/core.log:Dec 13 16:32:21 172.19.0.1 core[3330]: 2021-12-13T08:32:21Z [ERROR] [/common/config/manager.go:118]: loadSystemConfigFromEnv failed, config item, key: clair_db_port,  err: strconv.Atoi: parsing "": invalid syntax
/var/log/harbor/core.log:Dec 13 16:32:23 172.19.0.1 core[3330]: 2021-12-13T08:32:23Z [ERROR] [/common/config/manager.go:118]: loadSystemConfigFromEnv failed, config item, key: clair_db_port,  err: strconv.Atoi: parsing "": invalid syntax
/var/log/harbor/core.log:Dec 13 16:32:23 172.19.0.1 core[3330]: 2021-12-13T08:32:23Z [ERROR] [/common/config/manager.go:118]: loadSystemConfigFromEnv failed, config item, key: clair_db_port,  err: strconv.Atoi: parsing "": invalid syntax
/var/log/harbor/core.log:Dec 13 16:40:17 172.19.0.1 core[3330]: 2021-12-13T08:40:17Z [ERROR] [/common/config/manager.go:118]: loadSystemConfigFromEnv failed, config item, key: clair_db_port,  err: strconv.Atoi: parsing "": invalid syntax

5.查找/etc/passwd下除了含root以外的行

[root@server-01 ~]# grep -v root /etc/passwd

四、grep的进阶用法

1.显示/etc/passwd文件中以bash结尾的行

[root@server-01 ~]# grep "bash$" /etc/passwd
root:x:0:0:root:/root:/bin/bash
user1:x:2000:1000::/home/user1:/bin/bash

## 2.找出/etc/passwd文件中的三位或四位数

[root@server-01 ~]# egrep -w "[0-9]{3,4}" /etc/passwd
games:x:12:100:games:/usr/games:/sbin/nologin
systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin
systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin
polkitd:x:998:996:User for polkitd:/:/sbin/nologin
unbound:x:997:995:Unbound DNS resolver:/etc/unbound:/sbin/nologin
sssd:x:996:993:User for sssd:/:/sbin/nologin
chrony:x:995:992::/var/lib/chrony:/sbin/nologin
rngd:x:994:991:Random Number Generator Daemon:/var/lib/rngd:/sbin/nologin
user1:x:2000:1000::/home/user1:/bin/bash

3.查找/etc/grub2.cfg文件中,以至少一个空白字符开头,就免又跟了非空字符的行

[root@server-01 ~]# egrep "^[[:space:]]+[^[:space:]]" /etc/grub2.cfg

4.过滤文本中除了#开头和非空的行

[root@server-01 ~]#  grep -Evn '^#|^$' /etc/chrony.conf
2:server ntp.myhuaweicloud.com minpoll 4 maxpoll 10 iburst
5:stratumweight 0.05
8:driftfile /var/lib/chrony/drift
11:rtcsync
15:makestep 10 3
21:bindcmdaddress 127.0.0.1
22:bindcmdaddress ::1
28:noclientlog
31:logchange 0.5
33:logdir /var/log/chrony

5.取出ip地址

[root@server-01 ~]# ifconfig | egrep "inet\>"  | tr -s " " | cut -d" " -f3
172.21.0.1
172.19.0.1
172.20.0.1
172.17.0.1
192.168.200.150
127.0.0.1

6.过滤文本中的单词并统计频率

grep -o '\<[a-zA-Z]*[a-zA-Z]\>' /etc/passwd | sort | uniq -c | awk '{print $2,$1}'
相关文章
|
1天前
|
Linux 开发工具 Perl
|
3天前
|
运维 监控 Linux
提升系统稳定性:Linux内核参数调优实战
【5月更文挑战第1天】 在运维领域,保障服务器的高效稳定运行是核心任务之一。Linux操作系统因其开源、可靠和灵活的特点被广泛应用于服务器中。本文将深入探讨通过调整Linux内核参数来优化系统性能,提升服务器的稳定性和响应能力。文章首先介绍了内核参数调优的必要性和基本原则,然后详细阐述了调优过程中的关键步骤,包括如何监控当前系统状态,确定性能瓶颈,选择合适的参数进行调优,以及调优后的测试与验证。最后,文中提供了一些常见问题的解决策略和调优的最佳实践。
20 5
|
3天前
|
Linux
Linux系统ps命令
这些是一些常见的 `ps`命令选项和用法,用于查看系统中运行的进程及其相关信息。您可以根据需要选择合适的选项以满足您的任务要求。
12 0
|
4天前
|
存储 负载均衡 网络协议
在Linux中优化系统性能的实用指南
【4月更文挑战第30天】本文是关于Linux系统性能优化的指南,涵盖硬件选择、系统及软件更新、调整Swap分区、内核参数优化、使用性能分析工具、文件系统优化、网络服务优化和定期维护等方面。通过这些方法,可提升系统响应速度,降低资源消耗,延长硬件寿命。注意,优化需根据具体系统和应用需求进行。
|
4天前
|
弹性计算 Shell Linux
|
4天前
|
存储 缓存 Linux
linux几种典型应用对系统资源使用的特点
【4月更文挑战第22天】几种典型应用对系统资源使用的特点
11 0
|
25天前
|
缓存 Linux 测试技术
安装【银河麒麟V10】linux系统--并挂载镜像
安装【银河麒麟V10】linux系统--并挂载镜像
114 0
|
8月前
|
缓存 Ubuntu Linux
Vim编辑器入门指南:安装、基本操作和高级技巧详解 | 适用于Linux系统
Vim编辑器入门指南:安装、基本操作和高级技巧详解 | 适用于Linux系统
304 0
|
9月前
|
Oracle 关系型数据库 Linux
Virtualbox上安装Linux系统(CentOS7)(图文超详细)
Virtualbox上安装Linux系统(CentOS7)(图文超详细)
272 0
|
11天前
|
Linux 开发工具 Android开发
Docker系列(1)安装Linux系统编译Android源码
Docker系列(1)安装Linux系统编译Android源码
16 0