龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 操作系统 > LINUX系统 >

轻松学会文本处理工具之二 linux sed命令(12)

时间:2014-05-24 16:04来源:网络整理 作者:网络 点击:
分享到:
代码如下: [root@jie1 ~]# cat test #sed操作的文件中的内容 Ethernet #BOOTPROTO="dhcp" HWADDR="00:0C:29:90:79:78" ONBOOT="yes" IPADDR=172.16.10.12 NETMASK=255.255.0.0 [root@jie1 ~]# sed -i '


代码如下:

[root@jie1 ~]# cat test #sed操作的文件中的内容
Ethernet
#BOOTPROTO="dhcp"
HWADDR="00:0C:29:90:79:78"
ONBOOT="yes"
IPADDR=172.16.10.12
NETMASK=255.255.0.0
[root@jie1 ~]# sed -i 's/IPADDR/ip/w ip.txt' test
#把sed操作的文件内容保存到另外一个文件中,w表示保存,ip.txt文件名
[root@jie1 ~]# cat ip.txt #查看新文件的内容
ip=172.16.10.12
[root@jie1 ~]#


2)读取一个文件到正在用sed操作的文件中


代码如下:

[root@jie1 ~]# cat myfile #文件内容
hello world
i am li
how are you
li
[root@jie1 ~]# cat test #将用sed操作的文件的内容
Ethernet
#BOOTPROTO="dhcp"
HWADDR="00:0C:29:90:79:78"
ONBOOT="yes"
IPADDR=172.16.10.12
NETMASK=255.255.0.0
[root@jie1 ~]# sed -i '/Ethernet/r myfile' test
#在匹配Ethernet的行,读进来另一个文件的内容,读进来的文件的内容会插入到匹配Ethernet的行后
[root@jie1 ~]# cat test #再次查看用sed命令操作的行
Ethernet
hello world
i am li
how are you
li
#BOOTPROTO="dhcp"
HWADDR="00:0C:29:90:79:78"
ONBOOT="yes"
IPADDR=172.16.10.12
NETMASK=255.255.0.0
[root@jie1 ~]#

sed的经典例子:


代码如下:

##1)、处理以下文件内容,将域名取出并进行计数排序,如处理:
http://www.baidu.com/index.html
http://www.baidu.com/1.html
http://post.baidu.com/index.html
http://mp3.baidu.com/index.html
http://www.baidu.com/3.html
http://post.baidu.com/2.html
得到如下结果:
域名的出现的次数 域名
3 www.baidu.com
2 post.baidu.com
1 mp3.baidu.com
[root@localhost shell]# cat file | sed -e ' s/http:\/\///' -e ' s/\/.*//' | sort | uniq -c | sort -rn
3 www.baidu.com
2 post.baidu.com
1 mp3.baidu.com
[root@codfei4 shell]# awk -F/ '{print $3}' file |sort -r|uniq -c|awk '{print $1"\t",$2}'
3 www.baidu.com
2 post.baidu.com
1 mp3.baidu.com
##2)、用grep结合sed取出网卡的ip地址
[root@jie1 ~]# ifconfig | grep -B1 "inet addr" |grep -v "\-\-" |sed -n -e 'N;s/\(eth[0-9]\).*\n.*addr:\([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\).*/\1 \2/p'

学会sed的使用是写自动化shell脚本的基础,sed也是一个非常有用且重要的命令,是文本处理工具之一,以上是我自己学习总结的sed命令简单的用法,sed还有更高级的用法,也还在学习中。

精彩图集

赞助商链接