经过这两天sed的学习,发现其实sed其实挺简单的无非就是两句话来总结:sed是一种基于hold space和pattern space的逐句操作编辑器。
为什么这么说呢,通过学习不难发现,不管是grep ,sed都是利用正则表达式进行的操作,所以这里在学习shell编程前我们一定好好的学习正则表达式。
下来介绍一下我对sed的几点认识:首先就是搞清楚hold space和pattern space的概念。然后再了解sed的命令参数的意义,这样才能游刃有余。
下面是课后习题,1.把Jone的名字改为Jonathan。
zhouqian@zhou:~$ sed -n 's/^Jon/Jonathan/gp' test.txt Jonathan DeLoach:408-253-3122:123 Park St., San Jose, CA 04086:7/25/53:85100 zhouqian@zhou:~$ sed -n '/^Jon/{s/Jon/Jonathan/g;p;}' test.txt Jonathan DeLoach:408-253-3122:123 Park St., San Jose, CA 04086:7/25/53:85100 2.删除头3行。 sed '1,3d' test.txt3.打印第5-10行.这里我还弄错了呢,本以为是才3行呢,后来发现还包含了空格行。
![偷笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
5.打印所有生日在11月或12月的行 zhouqian@zhou:~$ sed -n '/\:1[12]\//p' test.txt teve Blenheim:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300 Karen Evich:284-758-2867:23 Edgecliff Place, Lincoln, NB 92743:11/3/35:58700 Karen Evich:284-758-2867:23 Edgecliff Place, Lincoln, NB 92743:11/3/35:58700 James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000 Barbara Kertz:385-573-8326:832 Ponce Drive, Gary, IN 83756:12/1/46:268500
6.在以Ered开头的行尾加上3颗星.$表示行尾的意思,&用来表示查到的匹配内容 zhouqian@zhou:~$ sed -n '/^Karen/{s/$/&***/gp}' test.txt Karen Evich:284-758-2857:23 Edgecliff Place, Lincoln, NB 92086:7/25/53:85100*** Karen Evich:284-758-2867:23 Edgecliff Place, Lincoln, NB 92743:11/3/35:58700*** Karen Evich:284-758-2867:23 Edgecliff Place, Lincoln, NB 92743:11/3/35:58700*** zhouqian@zhou:~$ sed -n '/^Karen/s/$/***/gp' test.txt Karen Evich:284-758-2857:23 Edgecliff Place, Lincoln, NB 92086:7/25/53:85100*** Karen Evich:284-758-2867:23 Edgecliff Place, Lincoln, NB 92743:11/3/35:58700*** Karen Evich:284-758-2867:23 Edgecliff Place, Lincoln, NB 92743:11/3/35:58700*** 7.将所有包含Jose的行都替换为JOSE HAS RETIRED sed '/Jose/c\JOSE HAS RETIRTED' test.txt Popeye Sailor:156-454-3322:945 Bluto Street, Anywhere, USA 29358:3/19/35:22350 JOSE HAS RETIRTED Tommy Savage:408-724-0140:1222 Oxbow Court, Sunnyvale, CA 94087:5/19/66:34200
8.把popeye的生日改为11/14/46,假定您不知道popeye的生日。这里我只想到了这一种方法,大家伙有人知道更好的方法请给我回复啊
![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)
9.删除所有空行 zhouqian@zhou:~$ sed '/^ *$/d' test.txt teve Blenheim:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300 Betty Boop:245-836-8357:635 Cutesy Lane, Hollywood, CA ,91464:6/23/23:14500 Igor Chevsky:385-375-8395:3567 Populus Place, Caldwell, NJ 23875:6/18/68:23400
10.将姓和名倒置
zhouqian@zhou:~$ sed 's/\([A-Z][a-z]*\) \([A-Z][a-z]*\):/\2 \1:/g' test.txt teve Blenheim:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300 Boop Betty:245-836-8357:635 Cutesy Lane, Hollywood, CA ,91464:6/23/23:14500 Chevsky Igor:385-375-8395:3567 Populus Place, Caldwell, NJ 23875:6/18/68:23400 Corder Norma:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700