副本

四剑客–grep⭐⭐⭐⭐⭐

过滤:在文件或管道中进行查找,找出想要的内容,默认按照行显示

   
   

 

 

grep ‘你想查找的内容’ 被查询的文件

  grep选项

grep选项 说明
-n line-number  显示行号
-v 排除、取反(将不含有的显示出来)
-i ignore-case  过滤的时候忽略大小写

 

  

 

 

案例与应用 

 1)基本用法

# 案例:在/etc/passwd中过滤出包含root的行
[root@yuan ~]# grep 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin # 案例:在/var/log/secure中过滤出包含Failed password的行并统计 [root@yuan ~]# grep 'session' /var/log/secure | wc -l 5

 2)显示内容和行号

# 案例:显示/etc/passwd中宝航root的行及行号
[root@yuan ~]# grep -n 'root' /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
10:operator:x:11:0:operator:/root:/sbin/nologin

 3)过滤的时候不区分大小写

# 案例:过滤出/var/log/secure中的failed password 的行且不区分大小写
[root@yuan ~]# grep -i 'failed password' /var/log/secure
Sep  9 19:54:21 yuan sshd[17674]: Failed password for root from 10.0.0.200 port 51568 ssh2
Sep  9 19:54:26 yuan sshd[17674]: Failed password for root from 10.0.0.200 port 51568 ssh2 Sep 9 19:54:29 yuan sshd[17674]: Failed password for root from 10.0.0.200 port 51568 ssh2

 4)排除

# 当查找的时候,不知道具体需要什么,但是你知道你什么不想要
    grep命令的排除选项,过滤出不包含xxx内容的行

# 案例:排除/etc/passwd中的nologin的行
[root@yuan ~]# grep -v 'nologin' /etc/passwd
root:x:0:0:root:/root:/bin/bash sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt

四剑客–find⭐⭐⭐⭐⭐

查找:在指定目录中查找文件

find  目录  指定类型  指定名字

  find选项

find命令选项 说明
-type 什么类型的文件(f表示文件,d表示目录)
-name 文件名
-size 根据大小查找文件(+表示大于、-表示小于)
-mtime 根据修改时间查找文件

 

 

 

 

 

  基础案例 

 1)精确查找与模糊查找

# 案例:在/etc/目录中找出文件名叫hostname文件
精确查找(指定文件名)
[root@yuan ~]# find /etc/ -type f -name 'hostname'
/etc/hostname # 案例:找出/etc/目录下面以.conf结尾的文件 模糊查找 [root@yuan ~]# find /etc/ -type f -name '*.conf' /etc/resolv.conf /etc/pki/ca-trust/ca-legacy.conf /etc/yum/pluginconf.d/fastestmirror.conf /etc/yum/pluginconf.d/langpacks.conf

 2)根据大小查找

  • -size选项,根据大小查找文件
    • 大于  使用+加号  -size +10k  大于10k的文件
    • 小于  使用-减号  -size -10k 小于10k的文件
# 案例:在/etc/目录下面找到大于1Mb的文件
[root@yuan ~]# find /etc/ -type f -size +1M
/etc/selinux/targeted/active/policy.kern
/etc/selinux/targeted/contexts/files/file_contexts.bin /etc/selinux/targeted/policy/policy.31 /etc/udev/hwdb.bin

 3)根据修改时间查找

# -mtime选项
    +7  找出7天前的文件
    -7   找出7天内的文件
# 案例:找出/etc/目录下以.conf结尾,7天之前的文件
[root@yuan ~]# find /etc/ -type f -name '*.conf' -mtime +7
/etc/pki/ca-trust/ca-legacy.conf
/etc/yum/pluginconf.d/fastestmirror.conf /etc/yum/pluginconf.d/langpacks.conf

 4)进阶选项

# 案例:查找文件时指定最多找多少层目录
[root@yuan ~]# find / -maxdepth 2 -type f -name '*.conf'
/etc/resolv.conf
/etc/asound.conf /etc/libuser.conf -maxdepth 2 :指定find命令查找的最大层数,不加上就是所有层 # 案例:查找的时候不区分文件名的大小写 find /   -type f -iname "*.conf" # ignore case

  find命令与其他命令配合(难点)⭐⭐⭐⭐⭐

请登录后发表评论

    没有回复内容