linux之sed命令

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011068702/article/details/88609634

1 sed命令(stream edit)

我们一般用来替换文件内容

2 常用方法

1)、比如一般用sed命令替换文件内容,这里参数-i的意思是操作后直接保存在file里面去了

sed -i 's/pattern/replace_str/' file

比如我们把sed.txt文件里面的chenyu替换成chen

cat sed.txt
chenyu
chencaifeng
chenyuan
chenyu
chenyu
chenyu


sed -i 's/chenyu/chen/' sed.txt


cat sed.txt
chen
chencaifeng
chenan
chen
chen
chen

2)删除文件的空白行

sed -i '/^$/d' sed1.txt

^¥匹配空白行,d是删除的意思

cat sed.txt
chen

chencaifeng
chenan

chen

chen
chen
sed -i '/^$/d' sed.txt
cat sed.txt
chen
chencaifeng
chenan
chen
chen
chen

3)替换从匹配的第几个参数开始

sed 's/pattern/newPlaceString/2g'

2就是第二个的意思,如果是3的话,就匹配第三个开始

echo thisthisthisthis | sed 's/this/THIS/2g'
thisTHISTHISTHIS
echo thisthisthisthis | sed 's/this/THIS/3g'
thisthisTHISTHIS

4)我们连续使用sed命令

echo abc | sed 's/a/A/' | sed 's/c/C/'
AbC

5)我们一般在脚本里面有变量的话,我们一般使用双引号

text=hello
echo hello world | sed "s/$text/HELLO/"
HELLO world

 

猜你喜欢

转载自blog.csdn.net/u011068702/article/details/88609634