常用选项:
-n∶只有经过sed 特殊处理的那一行才会被显示,通常和p一起使用
-e∶直接在指令列模式上进行 sed 的动作编辑
-f∶直接将 sed 的动作写在一个档案内
-r∶sed 的动作支援的是延伸型正规表示法的语法
-i∶直接修改读取的档案内容
常用命令:
a∶新增,在指定行后面插入字符串
c∶取代,替换指定行内容
d∶删除,删除指定行
i∶插入, 在指定行前面插入字符串
p∶列印,显示某一行,通过和-n一同使用
s∶取代,替换指定行中某个字符串内容
常用的使用见下面例子
删除
#删除第一行
sed '1d' hello.txt
删除最后一行
sed '$d' hello.txt
#删除第一行到第三行
sed '1,3d' hello.txt
#删除第二行到最后一行
sed '2,$d' hello.txt
#如果修改修改到原文件内容,加上-i
sed -i '1d' hello.txt
sed -i '$d' hello.txt
sed -i '1,3d' hello.txt
sed -i '2,$d' hello.txt
修改
#第一行后增加字符串"hello world"
sed '1a hello world' hello.txt
#第一行到第三行后增加字符串"hello world"
sed '1,3a hello world' hello.txt
#最后一行增加字符串"hello world"
sed '$a hello world' hello.txt
#第一行替换为"hello world"
sed '1c hello world' hello.txt
#第一行到第三行替换为"hello world"
sed '1,3c hello world' hello.txt
#最后一行替换为"hello world"
sed '$c hello world' hello.txt
替换每行第一个hello为world,第三个“/”后,不加参数就是只替换第一个
sed "s/hello/world/" hello.txt
替换每行所有的hello为world,第三个“/”后,加参数g就是替换所有
sed "s/hello/world/g" hello.txt
替换每行第二个hello为world,第三个“/”后,加参数2就是替换第2个
sed "s/hello/world/2" hello.txt
替换第一行第二个hello为world,第三个“/”后,加参数2就是替换第2个
sed "1s/hello/world/2" hello.txt
替换第一行到第三行第二个hello为world,第三个“/”后,加参数2就是替换第2个
sed "1,3s/hello/world/2" hello.txt
给每行行首加上hello(符号^代表行首)
sed 's/^/hello/' hello.txt
给每行行尾加上hello(符号^代表行首)
sed 's/$/hello/' hello.txt
多个替换动作,用分号;隔开可以一起执行
同时给所有行首加上hello,给所有行尾加上world
sed 's/^/hello/;s/$/world/' hello.txt
如果需要修改到原文件的加上-i
#第一行后增加字符串"hello world"
sed -i '1a hello world' hello.txt
#第一行到第三行后增加字符串"hello world"
sed -i '1,3a hello world' hello.txt
#最后一行增加字符串"hello world"
sed -i '$a hello world' hello.txt
#第一行替换为"hello world"
sed -i '1c hello world' hello.txt
#第一行到第三行替换为"hello world"
sed -i '1,3c hello world' hello.txt
#最后一行替换为"hello world"
sed -i '$c hello world' hello.txt
替换每行第一个hello为world,第三个“/”后,不加参数就是只替换第一个
sed -i "s/hello/world/" hello.txt
替换每行所有的hello为world,第三个“/”后,加参数g就是替换所有
sed -i "s/hello/world/g" hello.txt
替换每行第二个hello为world,第三个“/”后,加参数2就是替换第2个
sed -i "s/hello/world/2" hello.txt
替换第一行第二个hello为world,第三个“/”后,加参数2就是替换第2个
sed -i "1s/hello/world/2" hello.txt
替换第一行到第三行第二个hello为world,第三个“/”后,加参数2就是替换第2个
sed -i "1,3s/hello/world/2" hello.txt
给每行行首加上hello(符号^代表行首)
sed -i 's/^/hello/' hello.txt
给每行行尾加上hello(符号^代表行首)
sed -i 's/$/hello/' hello.txt
多个替换动作,用分号;隔开可以一起执行
同时给所有行首加上hello,给所有行尾加上world
sed -i 's/^/hello/;s/$/world/' hello.txt
显示
#显示第一行
sed -n '1p' hello.txt
#显示最后一行
sed -n '$p' hello.txt
#显示第一行到第三行
sed -n '1,3p' hello.txt
#显示第二行到最后一行
sed -n '2,$p' hello.txt
#显示包括hello所在所有行
sed -n '/hello/p' hello.txt
#查询包括$/所在所有行
sed -n '/\$\//p' hello.txt
斜杠/本身是作为sed语句中的分隔符,如果需要替换的字符串里也包含斜杠/,可以在前面加上\来进行转义,或者使用#和?来做分隔符(sed "s#hel/lo#world#" hello.txt)