[100]find&xargs命令

打算把基础命令常用选项做个总结.

find命令参数

- 命令格式
find . -type f -name '*.txt'

- 命令参数
find  #查找文件
-type #指定类型
            f 文件
            d 目录
- mtime #按照文件的修改时间查找文件
- name  #安装文件名称查找

!       #取反(排除某个文件)  find . -type f ! -name "*.txt"

-exec
find ...|args

find +exec/xargs的简单用途

- 移动1.md到/tmp下

方法1: exec方式
find . -type f -name '1.md' -exec mv {} /tmp/ \;
{}  # 代表前面找出的文件
\;  # 一些类unix需要转义


方法2: xargs(更简化点)
find . -type f -name '1.md'|xargs -i mv {} /tmp/

方法3:
mv `find . -type f -name '2.md'` /tmp/

参考

find根据时间戳查找

find干掉超过4天的

mtime 4天内 4天外
方法1:
find . -mtime +4 -exec rm -rf {} \;

方法2:
find . -mtime +4|xargs rm -f

清理超过30天的邮件

mkdir -p /root/shell

cat /root/shell/spool_clean.sh
#!/bin/sh

find/var/spool/clientmqueue/-type f -mtime +30|xargs rm -f

- 添加定时任务
echo '*/30 * * * * /bin/sh /server/scripts/spool_clean.sh >/dev/null 2>&1'>>/var/spool/cron/root

文件的(amc)atime,mtime,ctime区别

属性 解释
文件的 Access time atime 读取文件/执行文件 时更改的。如cat 1.log
文件的 Modified time mtime 写入文件时 随文件内容的更改而更改的。如echo 1 > alog
文件的 Create time ctime 写入文件/更改所有者/权限/链接 设置时随 Inode的内容更改而更改的。如ln -s if.sh if1.sh
影响范围及区别 atime >= ctime >= mtime
[root@n1 test]# touch temp
[root@n1 test]# stat temp
  File: ‘temp’
  Size: 0         	Blocks: 0          IO Block: 4096   regular empty file
Device: fd00h/64768d	Inode: 1045213     Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2018-03-02 09:06:10.943869915 +0800
Modify: 2018-03-02 09:06:10.943869915 +0800
Change: 2018-03-02 09:06:10.943869915 +0800
 Birth: -

根据文件大小进行匹配

find . -type f -size 文件大小单元

文件大小单元:

b - 块(512字节)
c - 字节
w - 字(2字节)
k - 千字节
M - 兆字节
G - 吉字节
- 搜索大于10KB的文件
find . -type f -size +10k
- 搜索小于10KB的文件
find . -type f -size -10k

xargs

从标准输入(管道或stdin,输入输出重定向)获取数据,并将数据转换为命令行参数

- n   指定输出行数

-i/-I 使用-I指定一个替换字符串{},这个字符串在xargs扩展时会被替换掉,当-I与xargs结合使用,每一个参数命令都会被执行一次;(轮询)

find ... |args -i {}
$ cat test.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z

- 默认输出一行
$ cat test.txt | xargs
a b c d e f g h i j k l m n o p q r s t u v w x y z

- -n指定每行输出
$ cat test.txt | xargs -n3
a b c
d e f
g h i
j k l
m n o
p q r
s t u
v w x
y z
posted @ 2018-03-02 08:41  _毛台  阅读(212)  评论(0编辑  收藏  举报