shell脚本删除指定行、插入指定位置行

将test.cfg文件中的name:lilei行删除,再插入name:hanmeimei

脚本:get_line_num.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/bin/bash
 
str=" name: hanmeimei"
 
## 显示现有的关键字行
cat test.cfg
 
## 获取关键字所在行
line_num=`cat -n test.cfg |grep name| awk '{print $1}'`
 
## 删除指定行
sed -i "${line_num}d" test.cfg
 
## 插入内容到指定行
sed -i "${line_num}i\ ${str}" test.cfg
 
## 显示插入后的关键字行
cat test.cfg|grep name

  注意:

  1.因为有变量,所以把sed常用的(‘)单引号换成(“)双引号,否则变量将原样输出。

  2.插入内容到指定行”i\ ${str}“的\和$中间有空格是为了让变量正确解释,如果没有空格变量将原样输出。

  3.插入内容到指定行里${str} 字符串也包含空格,如果不是用(“)双引号括起来,字符串里的空格也会被解释,就变成3个参数而报错。

  4.上面脚本还可以优化,比如cat -n 用sed -n ,但是为了方便理解,就分开写。

 

待插入内容的文件:test.cfg

1
2
3
4
City: china
age: 18
name: lilei
class: one

  

脚本执行:

1
sh get_line_num.sh

  

删除、插入结果:

1
2
3
4
City: china
age: 18
  name: hanmeimei
class: one

  

 

 

参考:

http://t.zoukankan.com/kakaisgood-p-8330578.html
https://my.oschina.net/bobwei/blog/1823639
https://www.csdn.net/tags/MtzaEgysMjE1NTYtYmxvZwO0O0OO0O0O.html

posted @   悟透  阅读(2392)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示