Linux下向一個文件中某行插入數據 以及 將多行文本轉換成一行並用逗號隔開

 

sed -i 'ni\x' test.file        表示向test.file文件裏的第n行的前面添加x內容
sed -i 'na\x' test.file       表示向test.file文件裏的第n行的後面添加x內容bash

sed -i '/m/i\x' test.file     表示向test.file文件裏匹配m字符串的行的前面添加x內容
sed -i '/m/a\x' test.file    表示向test.file文件裏匹配m字符串的行的後面添加x內容ssh

-i     表示in front,前面
-a    表示after,後面spa

好比向a.txt文件的首行添加123456789
# sed -i '1i\123456789' a.txtserver

好比向a.txt文件的第3行添加hhhhh
# sed -i '3a\hhhhh' a.txtblog

好比向a.txt文件匹配abcd字符串的行的前面添加66666
# sed -i '/abcd/i\66666' a.txt進程

好比向a.txt文件匹配1234字符串的行的後面添加hahaha
# sed -i '/1234/a\hahaha' a.txtip

好比向/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的腳本                                                           ast

[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

                                                          取文件中最後一個字符                                                                        class

取最後一個字符: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
相關文章
相關標籤/搜索