一、grep 行过滤工具
grep [选项] '关键字' 文件名
grep --color=auto 'root' passwd 过滤时关键字高亮显示
或添加别名:alias grep='grep --color=auto'
或修改文件:/etc/bashrc 添加上面一行
source /etc/bashrc
grep参数
grep -n 'root' passwd 包含root的行,打印行号
grep -ni 'root' passwd 忽略大小写匹配
grep '^root' passwd 以root开头的行
grep 'bash$' passwd 以bash结尾的行
grep -niv '^root' passwd 不以root开头的行,取反
grep -nB 3 '^ftp' passwd 以ftp开头的前三行
grep -nA 3 '^ftp' passwd 以ftp开头的后三行
grep -nC 3 '^ftp' passwd 以ftp开头的前后三行
grep -w 'hello' passwd 以hello单词为单位精准过滤
grep -o 'root' passwd 只打印关键字
二、cut 列截取工具
cut 选项 文件名
-c: 以字符为单位进行分割截取
-d: 自定义分隔符,默认为制表符\t
-f: 与-d一起使用,指定截取哪个区域
cut -d: -f1 passwd 截取以:分割的第一列
cut -d: -f1,7 passwd 截取以:分割的第一列和第七列
cut -c5-10 passwd 截取从第五个字符到第十个字符
用小工具列出当前系统的运行级别:
runlevel | cut -c3
grep -v '^#' /etc/inittab | cut -d: -f2
cut -d: -f2 /etc/inittab | tail -1
三、sort 排序
-u 去除重复行
-n 数字排序
-t 分隔符
-k 第N列
-r 降序排列
-o 结果重定向到文件
-b 忽略前导空格
-R 随机排序
sort -n -t: -k3 passwd 以:为分隔符按第三列数字排序
sort -nr -t: -k3 passwd 降序排列
sort -nr -t: -k3 passwd -o 1.txt 结果重定向到1.txt
四、uniq 去除连续重复行
-i 忽略大小写
-c 统计重复行次数
-d 只显示重复行
uniq 1.txt 去除连续重复行
五、tee 双向覆盖重定向(屏幕输出|文本输入)
echo hello world | tee 1.txt
echo 888999 | tee -a 1.txt 双向追加重定向
六、diff 逐行比较文件不同
diff [选项] 文件1 文件2
-b 不检查空格
-B 不检查空白行
-i 不检查大小写
-w 忽略所有空格
--normal 正常格式
-c 上下文格式显示
-u 合并格式显示
diff file1 file2 file1如何改变能和file2一样
diff -q dir1 dir2 比较目录里面的不同
**小技巧**:以一个文件为标准去修改其他文件,修改地方很多时,可以通过打补丁完成
diff -uN file1 file2 > file.patch
patch file1 file.patch
diff file1 file2
七、paste 合并文件行
-d 自定义间隔符,默认tab
-s 串行处理,非并行
paste file1 file2 两个文件内容以制表符隔开合并为一行
paste -d: file1 file2 以:隔开
paste -s file1 file2 以行为单位合并文件
八、tr 用于字符转换、替换和删除
-d 删除
-s 将重复出现的字符串压缩为一个字符串
a-z或[:lower:] 小写字母
A-Z或[:upper:] 大写字母
0-9或[:digit:] 数字
[:alnum:] 所有字母和数字
[:alpha:] 所有字母
tr 'a-z' 'A-Z' < 1.txt 小写字母替换成大写字母
tr ': /' '#' < 1.txt 单个匹配替换
tr -d 'a-z' < 1.txt
tr -d ': / 0-9,' < 1.txt 删除文件里面匹配的字符
tr -s 'a-z' < 1.txt 将文件中重复出现的小写字母字符串压缩为一个字符串
Practice
test1: 截取ip地址
ifconfig eth0 |grep 'Bcast' | cut -d: -f2 | tr -d 'a-zA-Z '
ifconfig eth0 |grep 'Bcast' | cut -d: -f2 | cut -d ' ' -f1
ifconfig eth0 |grep 'Bcast' | tr -d 'a-zA-Z:' | tr ' ' '\n' | grep -v '^$'
ifconfig eth0 | grep 'HW' | tr -s ' ' | cut -d ' ' -f5 截取MAC地址
test2:将普通用户的用户名、密码和默认shell保存到文件中,中间用tab隔开
grep 'bash$' passwd | grep -v 'root' | cut -d: -f1,2,7 | tr ':' '\t' | tee abc.txt