在Shell编程工具中,四剑客工具的使用更加的广泛,Shell编程四剑客包括:find、sed、grep、awk,熟练掌握四剑客会对Shell编程能力极大的提升。
四剑客之Find工具实战,Find工具主要用于操作系统文件、目录的查找,其语法参数格式为:
find path -option [ -print ] [ -exec -ok command ] { } \;
主要格式:
find [命令选项] [路径] [表达式选项]
其option常用参数详解如下:
name filename #查找名为filename的文件;
-type b/d/c/p/l/f #查是块设备、目录、字符设备、管道、符号链接、普通文件;
-size n[c] #查长度为n块[或n字节]的文件;
-perm #按执行权限来查找;
-user username #按文件属主来查找;
-group groupname #按组来查找;
-mtime -n +n #按文件更改时间来查找文件,-n指n天以内,+n指n天以前;
-atime -n +n #按文件访问时间来查找文件;
-ctime -n +n #按文件创建时间来查找文件;
-mmin -n +n #按文件更改时间来查找文件,-n指n分钟以内,+n指n分钟以前;
-amin -n +n #按文件访问时间来查找文件;
-cmin -n +n #按文件创建时间来查找文件;
-maxdepth #查找目录级别深度。
一、find工具-name案例:
[root@llody sh]# find /root/sh/ -name "*.txt" #查找/sh/目录下以.txt结尾的文件
[root@llody sh]# find /root/sh/ -name "[A-Z]*" #查找/sh/目录下以大写字母开头的文件
[root@llody sh]# find /root/sh/ -name "A*" #查找/sh/目录下以A开头的文件
二、find工具-type案例:
[root@llody sh]# find /root/sh/ -type d #查找/sh/目录下的文件夹
[root@llody sh]# find /root/sh/ ! -type d #查找/sh/目录下的非文件夹
[root@llody sh]# find /root/sh/ -type l #查找/sh/目录下的链接文件
[root@llody sh]# find /root/sh/ -type d|xargs chmod 755 -R #查目录类型并将权限设置为755
[root@llody sh]# find /root/sh/ -type f|xargs chmod 644 -R #查文件类型并将权限设置为644
三、find工具-size案例:
[root@llody sh]# find / -size +5M #查文件大小大于5Mb的文件
[root@llody sh]# find / -size 5M #查找文件大小等于5Mb的文件
[root@llody sh]# find / -size -5M #查找文件大小小于5Mb的文件
四、find工具-Mtime案例:
atime,access time #文件被读取或者执行的时间;
ctime,change time #文件状态改变时间;
mtime,modify time #文件内容被修改的时间;
[root@llody sh]# find /root/sh/ -mtime +30 -name "*.sh" #查找30天以前的sh文件
[root@llody sh]# find /root/sh/ -mtime -30 -name "*.sh" #查找30天内的sh文件
[root@llody sh]# find /root/sh/ -mtime 30 -name "*.sh" #查找等于30天的sh文件
[root@llody sh]# find /root/sh/ -mmin +30 -name "*.sh" #查找30分钟以前被修改过的sh文件
[root@llody sh]# find /root/sh/ -amin +30 -name "*.sh" #查找30分钟以前被访问过的sh文件
[root@llody sh]# find /root/sh/ -cmin 30 -name "*.sh" #查找第30分钟改变的sh文件
五、find工具参数综合案例:
[root@llody sh]# find /root/sh/ -name "*.sh" -type f -size +1k -exec cp {} /tmp/ \; #查找/sh/目录以.sh结尾,文件大于1k的文件,同时cp到/tmp目录
[root@llody sh]# find `pwd` -name "*.txt" -type f -size +10k -perm 644 -exec rm -f {} \; #查找/sh/目录下以.sh结尾,文件大于10K的文件,权限为644 并删除文件
[root@llody sh]# find `pwd` -name "*.txt" -mtime +30 -size +10M -exec mv {} /tmp/ \; # 查找/sh/目录下以.sh结尾,时间大于30天,文件大于10M,并移动到/tmp/目录下