sed指定某行插入、追加、全局替换
2016-04-11 11:18
211 查看
有时候会有这样的需求,在指定的行后面或者是前面追加一行,这个时候可以使用sed来完成,具体用法如下
a\ 在指定的行后面追加一行
b\ 在指定的行前面追加一行
### 使用指定的行号追加内容,在使用行号的过程中,需要注意的问题有以下
### N;后面只能使用偶数,且不可以为0
### a表示在指定的行后面追加一行
### i表示在当前行插入一行,如果指定行为4,其实最终的结果插入行的位置是第三行。
sed -i 'N;2a\newline' 1.txt
sed -i 'N;2i\newline' 1.txt
[root@lanmp shell]# cat << eof > 1.txt
> a
> b
> c
> d
> eof
[root@lanmp shell]# sed -i 'N;2a2222' 1.txt
[root@lanmp shell]# cat 1.txt
a
b
2222
c
d
[root@lanmp shell]# sed -i 'N;2i2222' 1.txt
[root@lanmp shell]# cat 1.txt
2222
a
b
2222
c
d
[root@RS2 shell]# cat 1.txt
1111
3333
[root@RS2 shell]# sed -i '/^1111$/a\2222' 1.txt ; cat 1.txt
1111
2222
3333
[root@RS2 shell]# sed -i '/^1111$/i\0000' 1.txt ; cat 1.txt
0000
1111
2222
3333
下面是把所有匹配的字符都替换为指定的字符
[root@SLAVE ~]# cat << eof > 1.txt
> 1111
> 222333333
> 44444444445
> eof
[root@SLAVE ~]# sed -i 2{s/2/3/g} 1.txt
[root@SLAVE ~]# cat 1.txt
1111
333333333
44444444445
[root@SLAVE ~]# sed -i 3{s/4/5/g} 1.txt
[root@SLAVE ~]# cat !$
cat 1.txt
1111
333333333
55555555555
a\ 在指定的行后面追加一行
b\ 在指定的行前面追加一行
### 使用指定的行号追加内容,在使用行号的过程中,需要注意的问题有以下
### N;后面只能使用偶数,且不可以为0
### a表示在指定的行后面追加一行
### i表示在当前行插入一行,如果指定行为4,其实最终的结果插入行的位置是第三行。
sed -i 'N;2a\newline' 1.txt
sed -i 'N;2i\newline' 1.txt
[root@lanmp shell]# cat << eof > 1.txt
> a
> b
> c
> d
> eof
[root@lanmp shell]# sed -i 'N;2a2222' 1.txt
[root@lanmp shell]# cat 1.txt
a
b
2222
c
d
[root@lanmp shell]# sed -i 'N;2i2222' 1.txt
[root@lanmp shell]# cat 1.txt
2222
a
b
2222
c
d
[root@RS2 shell]# cat 1.txt
1111
3333
[root@RS2 shell]# sed -i '/^1111$/a\2222' 1.txt ; cat 1.txt
1111
2222
3333
[root@RS2 shell]# sed -i '/^1111$/i\0000' 1.txt ; cat 1.txt
0000
1111
2222
3333
下面是把所有匹配的字符都替换为指定的字符
[root@SLAVE ~]# cat << eof > 1.txt
> 1111
> 222333333
> 44444444445
> eof
[root@SLAVE ~]# sed -i 2{s/2/3/g} 1.txt
[root@SLAVE ~]# cat 1.txt
1111
333333333
44444444445
[root@SLAVE ~]# sed -i 3{s/4/5/g} 1.txt
[root@SLAVE ~]# cat !$
cat 1.txt
1111
333333333
55555555555
相关文章推荐
- UIAutomatorview 简单封装 与 Appium Boostrap 结合
- rust 交叉编译平台: 在ubuntu上编译windows程序
- 逻辑同步软件对于只含有clob列的支持(HVR&OGG)
- 提高效率的Android Studio插件
- "A MultiPath Network for Object Detectio" 阅读笔记
- bootstrap的js相关
- Vs2012 创建后仍要求创建项目解决办法
- HTTP协议详解
- plSQL链接远程oracle
- Spring常用注解@Component、@Controller、@ Service、@ Repository......
- 软件工程
- 337. House Robber III
- JDBC 连接各种数据库的字符串
- ArrayList的contains方法与Object的equals方法的关系
- 9、数据的导入(mongoimport)和导出(mongoexport)---> 备份数据库的具体的集合
- unity3d 多语言切换插件 i2localization
- swift.h和briging文件冲突,重复包含
- 移动互联网公司如何将BPM流程管理变身移动化?
- 安装dotnet core
- Android 文件操作心得体会