Linux系统之grep命令基本使用

2023-11-29 13:21:49 浏览数 (1)

一、检查本地系统版本

代码语言:shell复制
[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"

二、grep的命令帮助

代码语言:shell复制
[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字符的文件

代码语言:shell复制
[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的文件

代码语言:shell复制
[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.过滤文件中的内容

代码语言:shell复制
[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.过滤文件中除了#和空开头的行

代码语言:shell复制
[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地址

代码语言:shell复制
[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$结尾的行

代码语言:shell复制
[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的行

代码语言:shell复制
[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"

我正在参与2023腾讯技术创作特训营第三期有奖征文,组队打卡瓜分大奖!

0 人点赞