sed命令使用

sed -n's@server_name\(.*\).qumaiyao.com;@& \1.ehaoyao.com;@p' im.conf

解析:

语句主体就是s替换

@ 就是平常的分隔符 /

\(.*\) \是转义,实际是表示   .* 匹配任意长度的任意字符,找出类似

server_name im.qumaiyao.com;

&符号表示替换换字符串中被找到的部份   (由于&后面没加东西所以显示的是server_name im.qumaiyao.com;

重要:.*查到的东西会被标记为:1,2,3,4类似

im就会被标记为1

由于&\1.ehaoyao.com所有.*匹配出来的东西就会替换成相应的 .ehaoyao.com打印出来

 

所以最后显示为:

server_name im.qumaiyao.com;       im. ehaoyao.com;

 

sed -n's@server_name\(.*\)\(.*\).qumaiyao.com;@& \1.ehaoyao.com;@p' im.conf

\(.*\)\(.*\)表示参数1与2

 

 

 

 

 

 

分割符号:

/  @

sed -n's@server_name\(.*\).qumaiyao.com;@& \1.ehaoyao.com;@p' im.conf

sed -n's/server_name\(.*\).qumaiyao.com;/& \1.ehaoyao.com;/p' im.conf

效果一样

 

 

 

 

替换:s命令

sed 's/this/x/' test

[admin@prepare-internal shell]$ sed 's/this/x/' test

x is the this  header data  line


sed 's/this/x/g' test

[admin@prepare-internal shell]$ sed 's/this/x/g' test

x is the x  header data  line

 

如果没有加g标记,则只替换每行第一个匹配,加g全部替换

 

 

打印:-n  -p

[admin@prepare-internal shell]$ sed 's/this/x/' test

x is the this  header data  line

thid is the second data  line

x is the last line

 

 

[admin@prepare-internal shell]$ sed -n 's/this/x/p' test

x is the this  header data  line

x is the last line

-n -p 一起使用只显示替换的行

 

命令:y
s替换的是整体,y替换的是每一字母对应的单个字母

sed '1,3y/abc/ABC/' dat把data中的第一行至第三行中的a换成A,b换成B,c换成C

1234567890   ABCDEFGHIJ

sed 's/01/Ab/g' test_sed

4567890123  456789Ab23

 

符号:&

sed 's/^192.168.0.1/&localhost/'example

&符号表示替换换字符串中被找到的部份。所有以192.168.0.1开头的行都会被替换成它自已加localhost,变成192.168.0.1localhost。

 

标记的使用

sed -n 's/\(love\)able/\1rs/p' example

love被标记为1,所有loveable会被替换成lovers,而且替换的行会被打印出来。

 

S后面的符号默认都是分隔符

sed 's#10#100#g' example

不论什么字符,紧跟着s命令的都被认为是新的分隔符,所以,“#”在这里是分隔符,代替了默认的“/”分隔符。表示把所有10替换成100

 

逗号选定行范围

sed -n '/test/,/check/p' example

所有在模板test和check所确定的范围内的行都被打印

 

从文件读入:r命令

sed '/test/r file' example

file里的内容被读进来,显示在与test匹配的行后面,如果匹配多行,则file的内容将显示在所有匹配行的下面。

 

 

 

写入文件:w命令

sed -n '/test/w file' example

example中所有包含test的行都被写入file里。

 

追加命令:a命令

$ sed '/^test/a\\--->this is a example' example

‘this is a example’被追加到以test开头的行后面,sed要求命令a后面有一个反斜杠。

 

插入:i命令

sed '/this/i\\new line-------------------------' test

如果test被匹配,则把反斜杠后面的文本插入到匹配行的前面

 

下一个:n命令

$ sed '/test/{ n; s/aa/bb/; }' example

如果test被匹配,则移动到匹配行的下一行,替换这一行的aa,变为bb,并打印该行,然后继续。

 

变形:y命令

$ sed '1,10y/abcde/ABCDE/' example

把1–10行内所有abcde转变为大写,注意,正则表达式元字符不能使用这个命令。

 

退出:q命令

$ sed '10q' example

打印完第10行后,退出sed。

 

保持和互换:h命令和x命令

$ sed -e '/test/h' -e '/check/x' example

互换模式空间和保持缓冲区的内容。也就是把包含test与check的行互换。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值