Linux常用命令之sed命令
文章目录
- Linux常用命令之sed命令
- 常用命令之`sed`
- 背景介绍
 
- 总结
作者简介
听雨:一名在一线从事多年研发的程序员,从事网站后台开发,熟悉java技术栈,对前端技术也有研究,同时也是一名骑行爱好者。
 Darren:一个工作经验用了N年的,资深划水人士,除了工作无其他爱好
口号:记录在开发中遇到日常问题、棘手问题的解法和思路
常用命令之sed
 
背景介绍
sed 是 “stream editor” 的缩写是一款强大的命令行工具,可以对文本文件进行编辑,可以减少很多重复的工作,而且可以避免vi或者vim中由于手滑导致的误操作。
常用参数
| 参数 | 解释 | 
|---|---|
| -i | 直接修改文本内容,而不输出到终端 | 
| -e | 直接在命令行指定要执行的脚本 | 
参考示例
 example.txt
root@master:~/temp# cat example.txt 
Hello World
Hello sed
Hello Unix
My name is Darren
He is TingYu
替换后输出屏幕
这种情况我一般是用于测试的情况,查看是否替换完成
root@master:~/temp/sed# sed 's/Hello/Hi/g' example.txt 
Hi World
Hi sed
Hi Unix
My name is Darren
He is TingYu直接替换
加上
-i参数后直接替换文本内容,做之前请记得备份文件,否则无法还原
root@master:~/temp/sed# sed -i 's/Hello/Hi/g' example.txt 
root@master:~/temp/sed# cat example.txt
Hi World
Hi sed
Hi Unix
My name is Darren
He is TingYuroot@master:~/temp/sed# 
在指定行前增加内容
root@master:~/temp/sed# sed  '1i This is Firstline' example.txt 
This is Firstline
Hi World
Hi sed
Hi Unix
My name is Darren
He is TingYuroot@master:~/temp/sed# 
在指定行后增加内容
root@master:~/temp/sed# sed  '1a This is Second line' example.txt 
Hi World
This is Second line
Hi sed
Hi Unix
My name is Darren
He is TingYuroot@master:~/temp/sed# 
删除行
root@master:~/temp/sed# sed '/Darren/d' example.txt
Hi World
Hi sed
Hi Unix
He is TingYu
删除2~4行
root@master:~/temp/sed# cat -n example.txt    1  Hi World2  Hi sed3  Hi Unix4  My name is Darren5  He is TingYu6
root@master:~/temp/sed# sed '2,4d' example.txt
Hi World
He is TingYuroot@master:~/temp/sed# 
匹配某行在行前增加
root@master:~/temp/sed# sed '/Darren/i In the line before you' example.txt
Hi World
Hi sed
Hi Unix
In the line before you
My name is Darren
He is TingYuroot@master:~/temp/sed# 
匹配某行在行后增加
root@master:~/temp/sed# sed '/Darren/a In the line after you' example.txt
Hi World
Hi sed
Hi Unix
My name is Darren
In the line after you
He is TingYuroot@master:~/temp/sed# 
只替换匹配的第一个值
root@master:~/temp/sed# sed '0,/Hi/s/Hi/Hello/' example.txt
Hello World
Hi sed
Hi Unix
My name is Darren
He is TingYuroot@master:~/temp/sed# 
匹配所有值
root@master:~/temp/sed# sed 's/Hi/Hello/g' example.txt
Hello World
Hello sed
Hello Unix
My name is Darren
He is TingYuroot@master:~/temp/sed# 
-e参数,可以执行多个脚本
root@master:~/temp/sed# sed -e 's/Hi/Hello/g' -e 's/Unix/Linux/g' example.txt
Hello World
Hello sed
Hello Linux
My name is Darren
He is TingYuroot@master:~/temp/sed# 
读取指定行
root@master:~/temp/sed# sed -n '2,4p'  example.txt
Hi sed
Hi Unix
My name is Darren
root@master:~/temp/sed# 
替换指定行的内容
root@master:~/temp/sed# cat -n example.txt1  Hi World2  Hi sed3  Hi Unix4  My name is Darren5  He is TingYu6
root@master:~/temp/sed# sed '2,3c haha' example.txt   
Hi World
haha
My name is Darren
He is TingYu
以上是常用的sed使用方式,分割符是/还可以使用#作为分隔符
总结
sed是强大的文本工具,可以管道符重定向等结合使用,从而达到快、准、狠编辑的效果。
参考:《Linux常用命令自学手册》