linux 中 实现数据中指定的行的内容批量替换

 

001、

[root@PC1 test4]# ls
a.txt  coordinate.txt
[root@PC1 test4]# cat a.txt                                     ## 测试数据
dd ff sd 1
ss aa ee 2
xx vv zz 3
ss ww rr 4
aa ff jj 5
nn mm kk 6
ss rr uu 7
yy uu ee 8
ww rr 88 9
[root@PC1 test4]# cat coordinate.txt                          ## 替换的数据
3 MMM 7777
5 GGG 3333
8 QQQ 2222
[root@PC1 test4]# cp a.txt a.txt.bak
[root@PC1 test4]# awk '{if(NR == 1) {print $1 - 1, $0; a=$1} else {print $1 - a - 1, $0; a=$1}}' coordinate.txt    ## 生成打印空行的索引
2 3 MMM 7777
1 5 GGG 3333
2 8 QQQ 2222
[root@PC1 test4]# awk '{if(NR == 1) {print $1 - 1, $0; a=$1} else {print $1 - a - 1, $0; a=$1}}' coordinate.txt > coordinate2.txt     ## 将打印空行的索引保存为文件
[root@PC1 test4]# cat coordinate2.txt
2 3 MMM 7777
1 5 GGG 3333
2 8 QQQ 2222
[root@PC1 test4]# cat coordinate2.txt | while read {i,j,k}; do seq $i | while read m; do echo "" >> temp; done; echo $k >> temp; done     ## 打印出空行
[root@PC1 test4]# ls
a.txt  a.txt.bak  coordinate2.txt  coordinate.txt  temp
[root@PC1 test4]# cat temp


MMM 7777

GGG 3333


QQQ 2222

 

 

002、

[root@PC1 test4]# ls
a.txt  a.txt.bak  coordinate2.txt  coordinate.txt  temp
[root@PC1 test4]# cat a.txt             ## 测试数据
dd ff sd 1
ss aa ee 2
xx vv zz 3
ss ww rr 4
aa ff jj 5
nn mm kk 6
ss rr uu 7
yy uu ee 8
ww rr 88 9
[root@PC1 test4]# cat temp         ## 替换的数据


MMM 7777

GGG 3333


QQQ 2222
[root@PC1 test4]# cat coordinate2.txt
2 3 MMM 7777
1 5 GGG 3333
2 8 QQQ 2222
[root@PC1 test4]# awk '{print ""}' a.txt | paste - temp | sed 's/^\s\+//' | paste - -d "&" a.txt | sed 's/^&//' | sed 's/&.*//'     ## 替换脚本
dd ff sd 1
ss aa ee 2
MMM 7777
ss ww rr 4
GGG 3333
nn mm kk 6
ss rr uu 7
QQQ 2222
ww rr 88 9

 

posted @ 2022-12-25 13:50  小鲨鱼2018  阅读(376)  评论(0编辑  收藏  举报