sed -i 'ni\x' test.file 表示向test.file文件里的第n行的前面添加x内容
sed -i 'na\x' test.file 表示向test.file文件里的第n行的后面添加x内容
sed -i '/m/i\x' test.file 表示向test.file文件里匹配m字符串的行的前面添加x内容
sed -i '/m/a\x' test.file 表示向test.file文件里匹配m字符串的行的后面添加x内容
-i 表示in front,前面
-a 表示after,后面
比如向a.txt文件的首行添加123456789
# sed -i '1i\123456789' a.txt
比如向a.txt文件的第3行添加hhhhh
# sed -i '3a\hhhhh' a.txt
比如向a.txt文件匹配abcd字符串的行的前面添加66666
# sed -i '/abcd/i\66666' a.txt
比如向a.txt文件匹配1234字符串的行的后面添加hahaha
# sed -i '/1234/a\hahaha' a.txt
比如向/etc/puppet/puppet.conf文件中的第2行的前面添加" server=puppet01.test.cn"内容
然后再向第3行添加" runinterval = 600"内容
# /bin/sed -i '2i\ server=puppet01.test.cn' /etc/puppet/puppet.conf
# /bin/sed -i '3i\ runinterval = 600' /etc/puppet/puppet.conf
远程批量关闭进程main的脚本
[root@kevn script]# cat 6_main_stop.sh #!/bin/bash for i in $(cat /opt/ip.list) do ssh -p22 root@$i 'ps -ef|grep main|grep -v grep|awk -F" " "{print $2}"|xargs kill -9 >/dev/null 2>&1' done
取文件中最后一个字符
取最后一个字符:awk '{print substr($0,length())}' filename [root@localhost ~]# cat a 3G 32G 123G 2348G 123131G 123123123123123G [root@localhost ~]# awk '{print substr($0,length())}' a G G G G G G [root@localhost ~]# awk -F"G" '{print $1}' a 3 32 123 2348 123131 123123123123123
将多行文本转换成一行并用逗号隔开
[root@kevin ~]# cat test 172.16.60.211 172.16.60.212 172.16.60.213 172.16.60.214 172.16.60.215 172.16.60.216 172.16.60.217 172.16.60.218 172.16.60.219 172.16.60.220 172.16.60.221 1)使用xargs方法,并用tr实现逗号隔开 [root@kevin ~]# cat test| xargs | tr ' ' ',' 172.16.60.211,172.16.60.212,172.16.60.213,172.16.60.214,172.16.60.215,172.16.60.216,172.16.60.217,172.16.60.218,172.16.60.219,172.16.60.220,172.16.60.221 2)使用sed实现多个字符串的替换。sed可以替换多个字符串,可以弥补tr的不足,后面g表示匹配多个。 [root@kevin ~]# cat test |xargs|sed 's/ /,/g' 172.16.60.211,172.16.60.212,172.16.60.213,172.16.60.214,172.16.60.215,172.16.60.216,172.16.60.217,172.16.60.218,172.16.60.219,172.16.60.220,172.16.60.221
将一行内容按照字段分为多列
[root@k8s-master01 ~]# cat a.txt 172.20.100.100,172.20.100.101,172.20.100.102,172.20.100.103,172.20.100.104,172.20.100.105,172.20.100.106 将逗号替换为换行 [root@k8s-master01 ~]# sed 's/,/\n/g' a.txt 172.20.100.100 172.20.100.101 172.20.100.102 172.20.100.103 172.20.100.104 172.20.100.105 172.20.100.106 [root@k8s-master01 ~]# sed -i 's/,/\n/g' a.txt [root@k8s-master01 ~]# cat a.txt 172.20.100.100 172.20.100.101 172.20.100.102 172.20.100.103 172.20.100.104 172.20.100.105 172.20.100.106