
文法:
sed [選項] [sed内置指令字元] [輸入檔案]
選項:
sed比對範圍
[[email protected] data]# cat -n luffycity.txt
1 My name is chaoge.
2 I teach linux.
3 I like play computer game.
4 My qq is 877348180.
5 My website is http://pythonav.cn.
[[email protected] data]# sed -n '2,3p' luffycity.txt
I teach linux.
I like play computer game.
#sed可以實作grep的過濾效果,必須吧要過濾的内容放在雙斜杠中
[[email protected] data]# sed -n '/linux/p' luffycity.txt
I teach linux.
[[email protected] data]# sed '/game/d' luffycity.txt
My name is chaoge.
I teach linux.
My qq is 877348180.
My website is http://pythonav.cn.
[roo[email protected] data]# sed -i '/game/d' luffycity.txt #不會輸出結果,直接寫入檔案
[[email protected] data]# sed '2,3d' luffycity.txt
删除第五行到結尾
[[email protected] data]# sed '5,$d' luffycity.txt
My name is chaoge.
----------
I teach linux.
----------
[[email protected] data]# sed 's/My/His/g' luffycity.txt
His name is chaoge.
I teach linux.
I like play computer game.
His qq is 877348180.
His website is http://pythonav.cn.
[[email protected] data]# sed -e 's/My/His/g' -e 's/877348180/88888/g' luffycity.txt
His name is chaoge.
I teach linux.
I like play computer game.
His qq is 88888.
His website is http://pythonav.cn.
[[email protected] data]# sed -i '2a I am useing sed command' luffycity.txt
My name is chaoge.
I teach linux.
I am useing sed command
I like play computer game.
My qq is 877348180.
My website is http://pythonav.cn.
[[email protected] data]# sed -i "3a i like linux very much.\nand you?" luffycity.txt
[[email protected] data]#
[[email protected] data]# cat -n luffycity.txt
1 My name is chaoge.
2 I teach linux.
3 I am useing sed command
4 i like linux very much.
5 and you?
6 I like play computer game.
7 My qq is 877348180.
8 My website is http://pythonav.cn.
[[email protected] data]# sed "a ----------" luffycity.txt
My name is chaoge.
----------
I teach linux.
----------
I am useing sed command
----------
i like linux very much.
----------
and you?
----------
I like play computer game.
----------
My qq is 877348180.
----------
My website is http://pythonav.cn.
----------
[[email protected] data]# sed '2i i am 27' luffycity.txt
My name is chaoge.
i am 27
----------
I teach linux.
----------
I am useing sed command
----------
i like linux very much.
----------
and you?
----------
I like play computer game.
----------
My qq is 877348180.
----------
My website is http://pythonav.cn.
----------
思路:
1.首先取出第二行
[[email protected] ~]# ifconfig | sed -n '2p'
inet 10.141.32.137 netmask 255.255.192.0 broadcast 10.141.63.255
2.找到第二行後,去掉ip之前的内容
[[email protected] ~]# ifconfig eth0|sed -n '2s#^.*inet##gp'
10.141.32.137 netmask 255.255.192.0 broadcast 10.141.63.255
解釋:
-n是取消預設輸出
2s是處理第二行内容
#^.*inet## 是比對inet前所有的内容
gp代表全局替換且列印替換結果
3.再次處理,去掉ip後面的内容
[[email protected] tmp]# sed -n '2s/^.*inet//gp' ip.txt | sed -n 's/net.*$//gp'
10.141.32.137
解釋:
net.*$ 比對net到結尾的内容
s/net.*$//gp #把比對到的内容替換為空
[[email protected] tmp]# ifconfig eth0 | sed -ne '2s/^.*inet//g' -e '2s/net.*$//gp'
10.141.32.137