Linux系统之grep命令基本使用

简介: Linux系统之grep命令基本使用

一、检查本地系统版本

[root@server001 ~]# cat /etc/os-release 
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

二、grepd的命令帮助

[root@server001 ~]# grep --help 
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: grep -i 'hello world' menu.h main.c

Regexp selection and interpretation:
  -E, --extended-regexp     PATTERN is an extended regular expression (ERE)
  -F, --fixed-strings       PATTERN is a set of newline-separated fixed strings
  -G, --basic-regexp        PATTERN is a basic regular expression (BRE)
  -P, --perl-regexp         PATTERN is a Perl regular expression
  -e, --regexp=PATTERN      use PATTERN for matching
  -f, --file=FILE           obtain PATTERN from FILE
  -i, --ignore-case         ignore case distinctions
  -w, --word-regexp         force PATTERN to match only whole words
  -x, --line-regexp         force PATTERN to match only whole lines
  -z, --null-data           a data line ends in 0 byte, not newline

Miscellaneous:
  -s, --no-messages         suppress error messages
  -v, --invert-match        select non-matching lines
  -V, --version             display version information and exit
      --help                display this help text and exit

Output control:
  -m, --max-count=NUM       stop after NUM matches
  -b, --byte-offset         print the byte offset with output lines
  -n, --line-number         print line number with output lines
      --line-buffered       flush output on every line
  -H, --with-filename       print the file name for each match
  -h, --no-filename         suppress the file name prefix on output
      --label=LABEL         use LABEL as the standard input file name prefix
  -o, --only-matching       show only the part of a line matching PATTERN
  -q, --quiet, --silent     suppress all normal output
      --binary-files=TYPE   assume that binary files are TYPE;
                            TYPE is 'binary', 'text', or 'without-match'
  -a, --text                equivalent to --binary-files=text
  -I                        equivalent to --binary-files=without-match
  -d, --directories=ACTION  how to handle directories;
                            ACTION is 'read', 'recurse', or 'skip'
  -D, --devices=ACTION      how to handle devices, FIFOs and sockets;
                            ACTION is 'read' or 'skip'
  -r, --recursive           like --directories=recurse
  -R, --dereference-recursive
                            likewise, but follow all symlinks
      --include=FILE_PATTERN
                            search only files that match FILE_PATTERN
      --exclude=FILE_PATTERN
                            skip files and directories matching FILE_PATTERN
      --exclude-from=FILE   skip files matching any file pattern from FILE
      --exclude-dir=PATTERN directories that match PATTERN will be skipped.
  -L, --files-without-match print only names of FILEs containing no match
  -l, --files-with-matches  print only names of FILEs containing matches
  -c, --count               print only a count of matching lines per FILE
  -T, --initial-tab         make tabs line up (if needed)
  -Z, --null                print 0 byte after FILE name

Context control:
  -B, --before-context=NUM  print NUM lines of leading context
  -A, --after-context=NUM   print NUM lines of trailing context
  -C, --context=NUM         print NUM lines of output context
  -NUM                      same as --context=NUM
      --group-separator=SEP use SEP as a group separator
      --no-group-separator  use empty string as a group separator
      --color[=WHEN],
      --colour[=WHEN]       use markers to highlight the matching strings;
                            WHEN is 'always', 'never', or 'auto'
  -U, --binary              do not strip CR characters at EOL (MSDOS/Windows)
  -u, --unix-byte-offsets   report offsets as if CRs were not there
                            (MSDOS/Windows)

'egrep' means 'grep -E'.  'fgrep' means 'grep -F'.


三、grep对文件的操作

1.在当前目录下过滤以.conf结尾且内容包含ssh字符的文件


[root@server001 etc]# grep ssh  *.conf 
kdump.conf:# ssh <user@server>
kdump.conf:# sshkey <path>
kdump.conf:#           - Will use the sshkey to do ssh dump.
kdump.conf:#             Specify the path of the ssh key to use when dumping
kdump.conf:#             via ssh. The default value is /root/.ssh/kdump_id_rsa.
kdump.conf:#             The default core_collector for raw/ssh dump is:
kdump.conf:#ssh user@my.server.com
kdump.conf:#sshkey /root/.ssh/kdump_id_rsa
sestatus.conf:/usr/sbin/sshd
sestatus.conf:/usr/sbin/sshd
sudo.conf:#Path askpass /usr/X11R6/bin/ssh-askpass
sudo.conf:#Path askpass /usr/libexec/openssh/gnome-ssh-askpass
updatedb.conf:PRUNEFS = "9p afs anon_inodefs auto autofs bdev binfmt_misc cgroup cifs coda configfs cpuset debugfs devpts ecryptfs exofs fuse fusesshfs fusectl gfs gfs2 gpfs hugetlbfs inotifyfs iso9660 jffs2 lustre mqueue ncpfs nfs nfs4 nfsd pipefs proc ramfs rootfs rpc_pipefs securityfs selinuxfs sfs sockfs sysfs tmpfs ubifs udf usbfs fuse.glusterfs ceph fuse.ceph"

2.查找在/etc目录下及子目录和文件中包含ssh.conf的文件

[root@server001 etc]# grep -r ssh.conf /etc/
/etc/ssh/ssh_config:#    $OpenBSD: ssh_config,v 1.30 2016/02/20 23:06:23 sobrado Exp $
/etc/ssh/ssh_config:# ssh_config(5) for more information.  This file provides defaults for
/etc/ssh/ssh_config:# ssh_config(5) man page.

四、过滤文件内容

1.过滤文件中的内容


[root@server001 etc]# grep *http* /var/log/*.log
/var/log/yum.log:Nov 03 13:11:42 Installed: httpd-tools-2.4.6-97.el7.centos.5.x86_64
/var/log/yum.log:Nov 03 13:11:42 Installed: httpd-2.4.6-97.el7.centos.5.x86_64

2.过滤文件中除了#和空开头的行


[root@server001 etc]# grep -Evn '^#|^$' /etc/ssh/sshd_config 
22:HostKey /etc/ssh/ssh_host_rsa_key
24:HostKey /etc/ssh/ssh_host_ecdsa_key
25:HostKey /etc/ssh/ssh_host_ed25519_key
32:SyslogFacility AUTHPRIV
47:AuthorizedKeysFile    .ssh/authorized_keys
65:PasswordAuthentication yes
69:ChallengeResponseAuthentication no
79:GSSAPIAuthentication yes
80:GSSAPICleanupCredentials no
96:UsePAM yes
101:X11Forwarding yes
126:AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
127:AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
128:AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
129:AcceptEnv XMODIFIERS
132:Subsystem    sftp    /usr/libexec/openssh/sftp-server


3.取出本机上的IP地址


[root@server001 etc]# ifconfig | egrep "inet\>"  | tr -s " " | cut -d" " -f3
172.27.0.1
192.168.48.1
172.20.0.1
172.29.0.1
192.168.32.1
172.26.0.1
172.23.0.1
172.18.0.1
172.22.0.1
172.30.0.1
172.28.0.1
172.19.0.1
172.25.0.1
172.17.0.1
192.168.3.166
127.0.0.1
192.168.122.1

4.过滤以bash$结尾的行

[root@server001 etc]# grep "bash$" /etc/passwd
root:x:0:0:root:/root:/bin/bash
admin:x:1000:1000:admin:/home/admin:/bin/bash
huawei:x:1020:1020::/home/huawei:/bin/bash
lisi:x:1021:1023::/home/lisi:/bin/bash

5.过滤文件中除了root的行

[root@server001 ~]# grep -v root /etc/containerd/config.toml 
#   Copyright 2018-2022 Docker Inc.

#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at

#       http://www.apache.org/licenses/LICENSE-2.0

#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

disabled_plugins = ["cri"]

#state = "/run/containerd"
#subreaper = true
#oom_score = 0

#[grpc]
#  address = "/run/containerd/containerd.sock"
#  uid = 0
#  gid = 0

#[debug]
#  address = "/run/containerd/debug.sock"
#  uid = 0
#  gid = 0
#  level = "info"

相关文章
|
18天前
|
存储 缓存 监控
Linux缓存管理:如何安全地清理系统缓存
在Linux系统中,内存管理至关重要。本文详细介绍了如何安全地清理系统缓存,特别是通过使用`/proc/sys/vm/drop_caches`接口。内容包括清理缓存的原因、步骤、注意事项和最佳实践,帮助你在必要时优化系统性能。
151 78
|
22天前
|
Linux Shell 网络安全
Kali Linux系统Metasploit框架利用 HTA 文件进行渗透测试实验
本指南介绍如何利用 HTA 文件和 Metasploit 框架进行渗透测试。通过创建反向 shell、生成 HTA 文件、设置 HTTP 服务器和发送文件,最终实现对目标系统的控制。适用于教育目的,需合法授权。
54 9
Kali Linux系统Metasploit框架利用 HTA 文件进行渗透测试实验
|
29天前
|
Linux Shell
Linux 10 个“who”命令示例
Linux 10 个“who”命令示例
53 14
Linux 10 个“who”命令示例
|
9天前
|
Linux
linux查看目录下的文件夹命令,find查找某个目录,但是不包括这个目录本身?
通过本文的介绍,您应该对如何在 Linux 系统中查看目录下的文件夹以及使用 `find` 命令查找特定目录内容并排除该目录本身有了清晰的理解。掌握这些命令和技巧,可以大大提高日常文件管理和查找操作的效率。 在实际应用中,灵活使用这些命令和参数,可以帮助您快速定位和管理文件和目录,满足各种复杂的文件系统操作需求。
32 8
|
18天前
|
Ubuntu Linux
Linux 各发行版安装 ping 命令指南
如何在不同 Linux 发行版(Ubuntu/Debian、CentOS/RHEL/Fedora、Arch Linux、openSUSE、Alpine Linux)上安装 `ping` 命令,详细列出各发行版的安装步骤和验证方法,帮助系统管理员和网络工程师快速排查网络问题。
104 20
|
9天前
|
监控 Linux 数据处理
Linux grep技巧 结合awk查询
结合 `grep` 和 `awk`,可以实现灵活、高效的文本处理和数据分析。`grep` 用于快速过滤符合条件的行,`awk` 用于进一步处理和提取数据。这种组合使用在日志分析、数据处理和系统监控等场景中尤为常见。掌握这两者的基本用法和组合技巧,可以大大提升在 Linux 环境下的工作效率。
29 7
|
18天前
|
存储 监控 Linux
嵌入式Linux系统编程 — 5.3 times、clock函数获取进程时间
在嵌入式Linux系统编程中,`times`和 `clock`函数是获取进程时间的两个重要工具。`times`函数提供了更详细的进程和子进程时间信息,而 `clock`函数则提供了更简单的处理器时间获取方法。根据具体需求选择合适的函数,可以更有效地进行性能分析和资源管理。通过本文的介绍,希望能帮助您更好地理解和使用这两个函数,提高嵌入式系统编程的效率和效果。
84 13
|
19天前
|
网络协议 Linux 应用服务中间件
kali的常用命令汇总Linux
kali的常用命令汇总linux
47 7
|
2月前
|
Linux 数据库
Linux中第一次使用locate命令报错?????
在Linux CentOS7系统中,使用`locate`命令时出现“command not found”错误,原因是缺少`mlocate`包。解决方法是通过`yum install mlocate -y`或`apt-get install mlocate`安装该包,并执行`updatedb`更新数据库以解决后续的“can not stat”错误。
37 9
|
2月前
|
监控 网络协议 Linux
Linux netstat 命令详解
Linux netstat 命令详解