记录了《Linux Shell脚本攻略》的笔记。
linux shell 常识
- cmd中0:标准输入,1标准输出,2是stderr,如:find / -name “*.conf” 2>>/dev/null
- cmd >out.file 2>&1 将stderr重定向到stdout
- cmd >out.file 2>1 将stderr重定向到文件1
2.4 文件查找与文件列表
find是最常用的命令之一,功能强大到一时难以掌握全部。
1.找出特定文件类型$ find -name "*.cpp" -print
#-iname 忽略大小写
$ find -iname "*.cpp" -print
#多个条件,用or(-o),也有and(-a)
$ find . -name "*.cpp" -o name "*.h" -print
2.4.1 使用-type查找指定文件类型的文件
文件类型 | 类型参数 |
---|---|
普通文件 | f |
符号链接 | l |
字符设备 | c |
块设备 | b |
套接字 | s |
Fifo | p |
目录 | d |
#查找socket文件 $ find . -type s #查找所有的目录 $ find . -type d #查找所有的一般文件 $ find . -type f #查找所有的隐藏文件 $ find . -type f -name ".*" #查找所有的隐藏目录 $ find -type d -name ".*" |
2.4.2目录深度设置
#当前一级查找即可 $ find . -maxdepth 1 -type f -print |
2.4.3与时间相关
单位是天
-atime:用户最近一次访问文件的时间。
-mtime:文件内容最后一次被修改的时间。
-ctime:文件元数据(metadata,例如权限或所有权)最后一次改变的时间。
符合后面可以添加整数,这些整数值通常还带有 - 或 + :- 表示小于,+ 表示大于。#最近(小于)7天内被访问的文件
$ find . -type -f -atime -7 -print
#最近访问时间超过7天
$ find . -type -f -atime +7 -print
单位是分钟
-amin:访问时间
-mmin:修改时间
-cmin:变化时间
-newer 找出比xxx还新的文件$ find -newer xxx
2.4.4与size相关
b —— 块(512字节)。
c —— 字节。
w —— 字(2字节)。
k —— 千字节。
M —— 兆字节。
G —— 吉字节。# 大于2KB的文件
$ find . -type f -size +2k
# 小于2KB的文件
$ find . -type f -size -2k
# 大小等于2KB的文件
$ find . -type f -size 2k
# 找出最大的5个文件
$ find . -type f -exec ls -s {} \; | sort -n -r | head -5
#找出非空的最小的5个文件
$ find . -not -empty -type f -exec ls -s {} \; | sort -n | head -5
#找出空文件
find . -empty
2.4.5查找到后的动作
find结合-exec可组合出最强大的执行动作,格式都是在find后添加-exec + your cmd + {} + \;
{}即为经过find匹配的文件名。$ find . -type f -size +2M -exec ls -thrl {} \;
#printf 和C的prinf一样具备格式化能力
$ find . -type f -name "*.txt" -exec printf "Text file: %s\n" {} \;
#将超过10天没人访问的文件拷贝到OLD目录
$ find . -type f -mtime +10 -name "*.txt" -exec cp {} OLD \;
#-exec后不能带多个命令,所以可以将多个命令组合放在sh文件中
$ find . -type f -mtime +10 -name "*.txt" -exec ./commands.sh {} OLD \;
2.5 xargs
xargs紧跟管道,将stdout转换为另个一命令的stdin。从生产力角度来说,有人认为xargs是最牛逼的命令之一。#将多行输入转换成单行输出
$ cat example.txt # 样例文件
1 2 3 4 5 6
7 8 9 10
11 12
$ cat example.txt | xargs
1 2 3 4 5 6 7 8 9 10 11 12
#-n 将输入转换为多行输出
cat example.txt | xargs -n 3
1 2 3
4 5 6
7 8 9
10 11 12
#最强大的{},与find的exec类似,xargs总是将{}替换为得到的参数。
#并行处理,将jpg转为png
ls *.jpg | xargs -I{} -P 8 convert "{}" `echo {} | sed 's/jpg$/png/'`
#bug ,hello world.txt会被认为是hello world.txt两个文件
$ find . -type f -name "*.txt" -print | xargs rm -f
#这样就可以删除所有的.txt文件。xargs -0将\0作为输入定界符。
$ find . -type f -name "*.txt" -print0 | xargs -0 rm -f