Linux 小三剑客 wc sort uniq
wc 统计
sort 排序
uniq 去重
Linux 三剑客 grep awk sed
grep 查询数据
类比SQL select * from table where field like “%a”
grep 常用参数
- -v 匹配不被pattern匹配的行
- -i 忽略大小写
- -n 显示匹配行号
- -c 统计匹配行数
- -o 仅显示匹配到的字符串
- -e 相当于egrep 多条件, 404|500, 200&201
grep 实战
- 查找文件内包含404 的行数
less nginx.log | grep 404 -n
- 查找文件内不包含404的行数
less nginx.log | grep 404 -nv
- 查找以s 开头的行
less nginx.log | grep '^n' -
- 查找以n 结尾的行
less nginx.log | grep 'n$' -
sed 数据更新
sed 是流编辑器,一次处理一行内容
sed -e 脚本
sed -f 脚本文件
类比SQL update fieldA from table where field = “abc”
sed 常用动作
- a 增加 sed -e ‘a 4 newline’
- c 取代
- d 删除
- i 插入之前
- p 打印
- s 替代, sed -e ‘s/old/new/g’
- g 全局替换
sed 实战
man sed || sed -h
- 在第四行后添加新的行 newline
sed -e ‘4 a newline’ practice.txt - 在第四行之前添加新的行 newline
sed -e ‘4 i newline’ practice.txt - 修改所有root 成curry
sed -ie ‘s/root/curry/g’ practice.txt
awk 数据切割
把文件逐行读入,以默认空格为分隔符将每行切片,切开的部分再进行后续处理。
类比SQL select fieldA from table
awk 常用参数
- -F 指定分隔符
- {} 括号内的是行为,比如awk ‘{print $1}’ 打印第一列,
- {} 括号外的是正则匹配,比如
- $0 $0 为全部行
- RS 控制記錄分隔符
- OFS 輸出與分隔符
- ORS 输出记录分隔符
awk 实战
- 打印/etc/password 下所有包含root的行,并且对应的shell (第七列)
awk -F: ‘/root/{print $7}’ /etc/password
[root@curry-qa-01 etc]# awk -F: '/root/{print $0}' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
- 打印第二行
awk -F: 'NR==2{print $0}' /etc/passwd
- 使用BEGIN加入指定列名
awk -F : 'BEGIN{print "BEGIN BEGIN"} {print $1,$2}' /etc/passwd
BEGIN BEGIN
root x
bin x
daemon x
adm x
lp x
sync x
shutdown x
halt x
mail x
operator x
games x
ftp x
nobody x
systemd-network x
dbus x
polkitd x
sshd x
postfix x
chrony x
nscd x
tcpdump x
- 以 | 分割字符串为行
echo "111 222|333 444|555 666" | awk 'BEGIN{RS="|"} {print $0}'
111 222
333 444
555 666