sed是一种流编辑器,是一款处理文本比较优秀的工具,可以结合正则表达式一起使用
sed执行过程
sed命令
命令: sed
语法 : sed [选项]... {命令集} [输入文件]...
常用命令:
d 删除选择的行
s 查找
y 替换
i 当前行前面插入一行
a 当前行后面插入一行
p 打印行
q 退出
替换符:
数字 :替换第几处
g : 全局替换
\1: 子串匹配标记,前面搜索可以用元字符集\(..\)
&: 保留搜索刀的字符用来替换其他字符
操作:
替换
查看文件:
[hzy@hzy ~]$ sed 's/little/big/' word
Twinkle, twinkle, big star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
When the blazing sun is gone
查看文本:
[hzy@hzy ~]$ cat word1
Oh if there's one thing to be taught
it's dreams are made to be caught
and friends can never be bought
Doesn't matter how long it's been
I know you'll always jump in
'Cause we don't know how to quit
全局替换:
[hzy@hzy ~]$ sed 's/to/can/g' word1
Oh if there's one thing can be taught
it's dreams are made can be caught
and friends can never be bought
Doesn't matter how long it's been
I know you'll always jump in
'Cause we don't know how can quit
删除:
查看文本:
[hzy@hzy ~]$ cat word
Twinkle, twinkle, little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
When the blazing sun is gone
删除:
[hzy@hzy ~]$ sed '2d' word
Twinkle, twinkle, little star
Up above the world so high
Like a diamond in the sky
When the blazing sun is gone
显示行号:
[hzy@hzy ~]$ sed '=;2d' word
1
Twinkle, twinkle, little star
2
3
Up above the world so high
4
Like a diamond in the sky
5
When the blazing sun is gone
删除第2行到第四行:
[hzy@hzy ~]$ sed '=;2,4d' word
1
Twinkle, twinkle, little star
2
3
4
5
When the blazing sun is gone
添加行:
向前插入:
[hzy@hzy ~]$ echo "hello" | sed 'i\kitty'
kitty
hello
向后插入:
[hzy@hzy ~]$ echo "kitty" | sed 'i\hello'
hello
kitty
修改行:
替换第二行为hello kitty
[hzy@hzy ~]$ sed '2c\hello kitty' word
Twinkle, twinkle, little star
hello kitty
Up above the world so high
Like a diamond in the sky
When the blazing sun is gone
替换第二行到最后一行为hello kitty
[hzy@hzy ~]$ sed '2,$c\hello kitty' word
Twinkle, twinkle, little star
hello kitty
写入行
把带star的行写入c文件中,c提前创建
[hzy@hzy ~]$ sed -n '/star/w c' word
[hzy@hzy ~]$ cat c
Twinkle, twinkle, little star
退出
打印3行后,退出sed
[hzy@hzy ~]$ sed '3q' word
Twinkle, twinkle, little star
How I wonder what you are
Up above the world so high