【打印】

nl /etc/issue | sed -n  '1,2p'


解释

1,2 指定行

p 打印的动作

-n 选项默认不输出。(sed 默认的是不匹配的也将输出) -n 选项和p行为时长一起出现。




【替换】

语法:sed ’s#正则#不可用正则表达式#g’  作用替换为空

如: 更改salt-minion配置文件  /etc/salt/minion  修改master和id

正常字符之间的替换

sed  -i  's/#master: salt/master: 10.59.72.1/g' /etc/salt/minion

使用系统变量的:

sed -i  "s/#id:/id: `hostname`/g"   /etc/salt/minion


【分组替换】

()起来的分组,可以使用\1代替第一个分组,\n代替第n个分组

ifconfig eth0 | sed -n 's#^.*inet addr:\(.*\)  Bcast.*$#\1#gp'


【替换】


【指定行插入】

首行插入

sed -i '1i\newlineword\n'  /etc/issue


指定行后面追加()

nl /etc/issue | sed '1,2i\insert oneline\n换行符'



解释:

1,2 行指定的位置

i 为 插入(在指定位置处插入)




【删除指定行】

把第一行第二行删除

nl /etc/issue | sed  '1,2d'  



【模式匹配地址】

匹配地址Addresses的方式有

1、地址行指定如 

    单行: 1

    多行: 1,2

    $表示最后一行:3,$

    addr1,+N: nl /etc/issue | sed -n  '1,+2p'

    addr1,~N: nl /etc/passwd | sed -n  '2,~3p'  从第二行开始到3的倍数为止

    first~step: nl /etc/passwd | sed -n  '2~3p' 打印first+N*step步长的行


2、正则匹配

    /regexp/ 正则匹配: nl /etc/issue | sed -n  '/[cC]ent[oO][sS]/p'

     

3、取反

    不匹配行的取反:nl /etc/passwd | sed -n  '/nologin/!p'

            nl /etc/passwd | sed  '/nologin/!d' 

    


实例: 打印奇数行

nl /etc/passwd | sed -n  '1~2p'


删除#开头的

sed  -e '/release/d' -e '/^#/d' file.cnf


 



【正则表达式】

特殊字符意义

&表示引用前面匹配的字符

# sed -i 's/root/(&)/g' test                   




[被替换的字符串中含有变量]

zone="ipo.com"

echo "a.txt.ip.cn| "sed "s#.$zone.##g"




[模式匹配行在替换]

匹配secondhandAgentDescription 字符串的行将\r\n字符替换成空

sed -i '/secondhandAgentDescription/s#\\r\\n##g' lianjia-secondhand_fang-aggregation-20180427220102.txt