sed
p打印
打印含有root行 (-n 只显示匹配处理的行 ) sed -n '/root/p' passwd.txt
第2行 sed -n 2p passwd.txt
a追加 ; i之前插入
第一行插入:sed '1i ewqewq' 1.txt
编辑追加 sed -i '2a 3123213' passwd.txt
编辑追加table: sed -i '2a \t cut' passwd.txt (\t tab键转义)
添加多行:sed -n '2a \t111\n\t222\n\t333' passwd.txt

image.png
echo 'jie_lun'| sed -r 's/(^.)_(.$)/\2 123 \1/g'
[root@hecs-332182 shell]# ip a s eth0| sed -n '3p'| sed -r 's/^.t(.)/.*/\1/g'
192.168.0.185
c修改 或者///
匹配内容修改 sed -i '/^SELINUX=/c SELINUX=disabled' /etc/selinux/config
指定行修改 sed -i '7c SELINUX=disabled' /etc/selinux/config
sed -i 's/SELINUX=disabled/SELINUX=disabled1/g' /etc/selinux/config
d删除
删除3-最后一行 sed '3,$d' 1.txt
删除第3行 sed '3' 1.txt
awk:
以:分隔符,过滤每行的第一列,开始前打印ks,结束打印js。
cat passwd.txt| awk -F ':' 'BEGIN{print "ks"} {print $1} END {print "js"}'
判断大于输出:
df | awk '/\/$/ {if ($3>20) {print $4}}'
NR 行:
awk 'NR==3{print $1}' passwd.txt
date | awk '{print "年份:" $1"\n" "月份:"$2}'
printf函数:
%s 字符类型 %d数值类型 -左对齐(默认是右)
printf不会自动换行,需要家\n
eg:awk -F: '{printf "%-15s %-10s\n",$1,$2}' /etc/passwd
[root@hecs-332182 shell]# ll| awk '{print $5,$9}'| column -t
1265 111.txt
236 123.txt
16 1.txt
343 2022-06-01.log

image.png
第三列1开头
[root@hecs-332182 shell]# awk -F: '$3~/^1/' passwd.txt
bin:x:1:1:bin:/bin:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin.
第三列包含1或者2
[root@hecs-332182 shell]# awk -F: '$3~/^[12]/ {print $1,$3,$NF}' passwd.txt| column -t
bin 1 /sbin/nologin
#daemon 2 /sbin/nologin
operator 11 /sbin/nologin.

image.png
END使用
[root@hecs-332182 shell]# awk '/^$/{i++}END{print i}' passwd.txt
4
[root@hecs-332182 shell]# seq 10
1
2
3
4
5
6
7
8
9
10
[root@hecs-332182 shell]# seq 10| awk '{sum=sum+$0}END{print sum}'
55
数组:

image.png
[root@hecs-332182 shell]# awk '{print $1}' mp.bytmall.cn.access.log |sort| uniq -c| sort -rn | head -5
196 "110.176.47.114"
192 "117.136.68.14"
175 "117.136.33.192"
110 "101.91.60.91"
106 "223.104.68.126"
[root@hecs-332182 shell]# awk 'BEGIN{a[0]=123;a[1]="jay";a[3]="cyx"; for (i in a) print a[i]}'
123
jay
cyx
例子:-------
[root@hecs-332182 shell]# cat 1.txt
http://www.123.com/1.html
http://www.456.com/1.html
http://www.789.com/1.html
http://www.124.com/1.html
http://www.123.com/1.html
http://www.123.com/1.html
http://www.124.com/1.html
[root@hecs-332182 shell]# awk -F '/' '{print $3}' 1.txt | sort | uniq -c | sort -rn
3 www.123.com
2 www.124.com
1 www.789.com
1 www.456.com
----
[root@hecs-332182 shell]# awk -F '/' '{array[$3]++}END{for(i in array) print i,array[i]}' 1.txt
www.789.com 1
www.456.com 1
www.124.com 2
www.123.com 3
for循环:
[root@hecs-332182 shell]# awk 'BEGIN{for(i=1;i<=100;i++) sum+=i;print sum}'
5050
if语句:
[root@hecs-332182 shell]# awk -F '\"' '{if($10==302)print $0}' mp.bytmall.cn.access.log | wc -l
145
[root@hecs-332182 log]# df -h| awk -F"[ %]+" 'NR>1{if($5>60)print $0 } '
/dev/vda1 40G 26G 12G 70% /
[root@hecs-332182 log]# echo i am wangjie good boy mandfnsa ewqrwq |awk '{for(i=1;i<=NF;i++)if(length($i)>3)print $i}'
wangjie
good
mandfnsa
ewqrwq