6-2 9 sed

原创
2017/09/05 21:59
阅读数 87

9.4/9.5 sed

sed是正则表达式工具之一,非常适合对txt文本行进行调整并输出

语法:

1. sed  '/xxx/'p -n txt 匹配-输出
2. sed  '/xxx/'d txt    匹配-不输出
3. sed  ' x,y 'p -n txt 匹配-输出 			
4. sed s'/xxx/yyy/' txt 替换-输出 一行一次
5. sed s'/xxx/yyy/' g txt  替换-输出 一行多次
6. sed s'/(x)/yyy/' -r txt 替换-输出 包含正则
7. sed s'/xxx/yyy/' -i txt 替换-修改 谨慎使用
8. sed s'/(x1)(x2)(x3)/\3\2\1/' -r txt 替换-输出 调换位置
9. sed -e '/xxx/'p -e '1,10'p -n txt 匹配-输出 多次匹配

高能用法:

  • /(.*)/#&/
    • 整行匹配,&表示原行,替换效果为行首加#
  • /xxx//
    • 将xxx替换为空,效果为删除
  • /([^:]+)(:.*:)([^:]+)/\3\2\1/
    • (1)匹配第一个:前的字符串,
    • (2)匹配两个:及之间的字符串,贪婪匹配让第二个冒号表示最后一个冒号
    • (3)表示最后一个:后的字符串

举例:

打印x-y行 sed -n 'x,y'p file

[root@axiang-03 ~]# sed -n '3,10'p test.txt  
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin

打印有xx的行 sed n '/xx/'p file

[root@axiang-03 ~]# sed -n '/root/'p test.txt 
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

打印以xx结尾的行 sed n '/xx$/' file

[root@axiang-03 ~]# sed -n '/in$/'p test.txt
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

替换xx为yy sed 's/xx/yy/g' file

[root@axiang-03 ~]# sed 's/olo/nnnnggggg/g' test.txt 
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nnnnnggggggin
daemon:x:2:2:daemon:/sbin:/sbin/nnnnnggggggin
adm:x:3:4:adm:/var/adm:/sbin/nnnnnggggggin

删除xx sed 's/xx//g' file

[root@axiang-03 ~]# sed 's/[0-9a-r]//g' test.txt | sed -n '6,7'p 
sy:x:::sy:/s://sy
sutw:x:::sutw:/s:/s/sutw

调换行内第一个xx和最后一个yy sed -r 's/(xx)(.*)(yy)/\3\2\1/' file

[root@axiang-03 ~]# sed -r 's/(root)(.*)(bash)/\3\2\1/' test.txt |sed -n '1'p 
bash:x:0:0:root:/root:/bin/root 

行首加入xx sed 's/^.*$/xx&/' file

[root@axiang-03 ~]# sed 's/^.*$/666&/' test.txt  行首加字符 不需要g 
666root:x:0:0:root:/root:/bin/bash
666bin:x:1:1:bin:/bin:/sbin/nologin

第一组数字和最后一组英文字符调换位置

[root@axiang-03 ~]# cat 2.txt  
111eoajfe eoxiua eown  aaa
efae 222 wonf ;fafpeona bbb 323
!#werw@$333weronoanfe$@#%ccc@!#342 
[root@axiang-03 ~]# sed -r 's/([0-9]+)(.*[^a-zA-Z])([a-zA-Z]+)/\3\2\1/' 2.txt 
aaaeoajfe eoxiua eown  111
efae bbb wonf ;fafpeona 222 323
!#werw@$cccweronoanfe$@#%333@!#342
解释:贪婪匹配,保证最后条件匹配成功且最小匹配。这里如果没有停止条件,只会留给最后条件一个字符
第一个数移动到行尾
[root@axiang-03 ~]# sed -r 's/([0-9]+)(.*)/\2\1/' test.txt

场景举例,转变电话号格式

root@lixiang01:~# cat distros.txt
Ubuntu     8.04    04/24/2008 
Fedora     8      11/08/2007 
Ubuntu     6.10    10/26/2006 
root@lixiang01:~# sed -r 's/([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/\3-\1-\2/' distros.txt 或者加入-r选项,但是匹配文本中的“/”依然需要转义
Ubuntu     8.04    2008-04-24
Fedora     8      2007-11-08
Ubuntu     6.10    2006-10-26
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部