sed 常用操作
特殊符号
- ”*“ 号代表重复自己前面的字符,可重复0个或者多个字符
- ”.“ 号代表任意一个字符,只能匹配一个字符
- ”?“ 号代表重复自己前面的字符,可重复0个或者一个字符
- ”+“ 号代表重复自己前面的字符,可重复1个或者多个字符
用法
-i 直接编辑并修改文件,并改变文件原内容
-e 不直接编辑文件,而是在执行终端输出改变的结果
-n 静默输出,只输出结果,不输出过程
删除操作
- 删除指定行(删除第2行)
sed -i '2d' file_name
- 删除连续行,如下
sed -i '2,5d' file_name
- 删除非连续行
sed -i '2d;3d;4d' file_name
- 删除最后一行
sed -i '$d' file_name
- 删除匹配行,如下
sed -i '/匹配字符/d' file_name
过滤操作
- 查看最后一行操作
<root@HK-K8S-CP ~># kubectl get nodes NAME STATUS ROLES AGE VERSION hk-k8s-cp Ready master 499d v1.19.16 hk-k8s-wn1 Ready worker 499d v1.19.16 hk-k8s-wn2 Ready worker 498d v1.19.16 hk-k8s-wn3 Ready worker 498d v1.19.16 ## 过滤最后一行 <root@HK-K8S-CP ~># kubectl get nodes | sed -n '$p' hk-k8s-wn3 Ready worker 498d v1.19.16 ## nl方式带行号输出 <root@HK-K8S-CP ~># kubectl get nodes | nl | sed -n '$p' 5 hk-k8s-wn3 Ready worker 498d v1.19.16 ## tail方式输出最后一行 <root@HK-K8S-CP ~># kubectl get nodes | tail -n 1 hk-k8s-wn3 Ready worker 498d v1.19.16 ## awk输出最后一行 <root@HK-K8S-CP ~># kubectl get nodes | awk 'END{print NR,$0}' 5 hk-k8s-wn3 Ready worker 498d v1.19.16
- 查看指定行
<root@HK-K8S-CP ~># kubectl get nodes | sed '1p' NAME STATUS ROLES AGE VERSION hk-k8s-cp Ready master 499d v1.19.16 hk-k8s-wn1 Ready worker 499d v1.19.16 hk-k8s-wn2 Ready worker 498d v1.19.16 hk-k8s-wn3 Ready worker 498d v1.19.16 <root@HK-K8S-CP ~># kubectl get nodes | sed -n '3p' hk-k8s-wn1 Ready worker 499d v1.19.16
## awk查看指定行号<root@HK-K8S-CP ~># kubectl get nodes | awk -n NR==2
hk-k8s-cp Ready master 499d v1.19.16 - 查看连续行
<root@HK-K8S-CP ~># kubectl get nodes | sed -n '2,3p' hk-k8s-cp Ready master 499d v1.19.16 hk-k8s-wn1 Ready worker 499d v1.19.16
- 查看输出的总行
<root@HK-K8S-CP ~># kubectl get nodes | awk -n '{print NR}' 1 2 3 4 5 <root@HK-K8S-CP ~># kubectl get nodes | awk '{print NR}' 1 2 3 4 5 <root@HK-K8S-CP ~># kubectl get nodes | awk 'END{print NR}' 5 <root@HK-K8S-CP ~># kubectl get nodes | sed -n '$=' 5
- 过滤匹配的行
<root@HK-K8S-CP ~># kubectl get nodes NAME STATUS ROLES AGE VERSION hk-k8s-cp Ready master 499d v1.19.16 hk-k8s-wn1 Ready worker 499d v1.19.16 hk-k8s-wn2 Ready worker 498d v1.19.16 hk-k8s-wn3 Ready worker 498d v1.19.16
## 输出匹配指定字符的行 <root@HK-K8S-CP ~># kubectl get nodes | sed -n '/hk-k8s-cp/p' hk-k8s-cp Ready master 499d v1.19.16
## 输出匹配字符的行并带行号 <root@HK-K8S-CP ~># kubectl get nodes | sed -n '/hk-k8s-cp/{=;p}' |tr -d "\n" | awk '{printf $0"\n"}' 2hk-k8s-cp Ready master 499d v1.19.16
<root@HK-K8S-CP ~># kubectl get nodes | sed -n '/hk-k8s-cp/{=;p}' |tr -d "\n" 2hk-k8s-cp Ready master 499d v1.19.16<root@HK-K8S-CP ~># - 输出匹配的连续行
<root@HK-K8S-CP ~># kubectl get nodes | nl | sed -n '/hk-k8s-wn/{3,4p}' 3 hk-k8s-wn1 Ready worker 499d v1.19.16 4 hk-k8s-wn2 Ready worker 498d v1.19.16