s Dalsass 2.7 .8 2 18 southeast SE Patricia 4.0 .7 4 17 eastern EA TB Savage 4.4 .84 5 20 northeast NE AM Main Jr. 5.1 .94 3 13 north NO Margot Weber 4.5 .89 5 9 central CT Ann Stephens 5.7 .94 5 13 [windriver@windriver-machine ltest]$ sed ''/SO/!d'' datafile southern SO Suan chin 5.1 .95 4 15 [windriver@windriver-machine ltest]$ sed对文件的修改方式,通常SED编辑的是缓冲区内容,然后将编辑后的结果显示在屏幕上,因此对原文件不破坏,因此,如果要真正写回到原文件,需要重定向到一个新文件,然后拷贝回去. [windriver@windriver-machine ltest]$ sed ''1,3d'' datafile >temp [windriver@windriver-machine ltest]$ cat temp southern SO Suan chin 5.1 .95 4 15 southeast SE Patricia 4.0 .7 4 17 eastern EA TB Savage 4.4 .84 5 20 northeast NE AM Main Jr. 5.1 .94 3 13 north NO Margot Weber 4.5 .89 5 9 central CT Ann Stephens 5.7 .94 5 13 [windriver@windriver-machine ltest]$ sed -i ''1,3d'' temp [windriver@windriver-machine ltest]$ cat temp northeast NE AM Main Jr. 5.1 .94 3 13 north NO Margot Weber 4.5 .89 5 9 central CT Ann Stephens 5.7 .94 5 13 [windriver@windriver-machine ltest]$ 当然SED可以使用选项-i进行in place修改. SED操作的退出状态,成功是0,一般的失败是1,如果有报错信息的,通常是需要根据错误信息进行语法修改. [windriver@windriver-machine ltest]$ sed ''1,3d'' datafile southern SO Suan chin 5.1 .95 4 15 southeast SE Patricia 4.0 .7 4 17 eastern EA TB Savage 4.4 .84 5 20 northeast NE AM Main Jr. 5.1 .94 3 13 north NO Margot Weber 4.5 .89 5 9 central CT Ann Stephens 5.7 .94 5 13 [windriver@windriver-machine ltest]$ echo $? 0 [windriver@windriver-machine ltest]$ sed ''1,3f'' datafile sed: -e expression #1, char 4: unknown command: `f'' [windriver@windriver-machine ltest]$ echo $? 1 [windriver@windriver-machine ltest]$ SED正则表达式,同GREP类似,GREP缺省的元字符,SED都支持,但SED还支持一些特殊的元字符,如下表所示: & | 保存查找字符串,这样在后面可以对这个字符串进行替换(这个有点类似于前面\(\) \r | s/love/**&**/ | love这个字符串被**love**字符串替换 | | | | | | | | | | | | | [windriver@windriver-machine ltest]$ sed ''s/CT/**&**/'' datafile northwest NW Charles Main 3.0 .90 3 34 western WE Sharon Gray 5.3 .97 5 23 southwest SW Lewis Dalsass 2.7 .8 2 18 southern SO Suan chin 5.1 .95 4 15 southeast SE Patricia 4.0 .7 4 17 eastern EA TB Savage 4.4 .84 5 20 northeast NE AM Main Jr. 5.1 .94 3 13 north NO Margot Weber 4.5 .89 5 9 central **CT** Ann Stephens 5.7 .94 5 13 [windriver@windriver-machine ltest]$ sed ''s/north/&ing/g'' datafile northingwest NW Charles Main 3.0 .90 3 34 western WE Sharon Gray 5.3 .97 5 23 southwest SW Lewis Dalsass 2.7 .8 2 1 |