Sed-命令详解.doc_第1页
Sed-命令详解.doc_第2页
Sed-命令详解.doc_第3页
Sed-命令详解.doc_第4页
Sed-命令详解.doc_第5页
已阅读5页,还剩14页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Sed 命令详解1.sed-n2pfilename打印文件的第二行。2.sed-n1,3pfilename打印文件的1到3行3.sed-n/Neave/pfilename打印匹配Neave的行(模糊匹配)4.sed-n4,/The/pfilename在第4行查询模式The5.sed-n1,$pfilename打印整个文件,$表示最后一行。6.sed-n/.*ing/pfilename匹配任意字母,并以ing结尾的单词(点号不能少)7sed-n/-e/music/=filename打印匹配行的行号,-e会打印文件的内容,同时在匹配行的前面标志行号。-n只打印出实际的行号。8.sed-n-e/music/p-e/music/=filename打印匹配的行和行号,行号在内容的下面9.sed/company/aThensuddenlyithappendfilename选择含有company的行,将后面的内容Thensuddenlyithappend加入下一行。注意:它并不改变文件,所有操作在缓冲区,如果要保存输出,重定向到一个文件。10.sed/company/iThensuddenlyithappendfilename同9,只是在匹配的行前插入11.sed/company/cThensuddenlyithappendfilename用Thensuddenlyithappend替换匹配company的行的内容。12.sed1d(1,3d$d/Neave/d)filename删除第一行(1到3行,最后一行,匹配Neave的行)13.address,addresss/pattern-to-find/replacement-pattern/gpwns选项通知sed这是一个替换操作,并查询pattern-to-find,成功后用replacement-pattern替换它。替换选项如下:g缺省情况下只替换第一次出现模式,使用g选项替换全局所有出现模式。p缺省sed将所有被替换行写入标准输出,加p选项将使-n选项无效。-n选项不打印输出结果。w文件名使用此选项将输出定向到一个文件。(注意只将匹配替换的行写入文件,而不是整个内容)14.seds/nurse/hello&/filename将hello增加到nurse的前面。15.sed/company/rappend.txtfilename在匹配company的行的下一行开始加入文件append.txt的内容。16.sed/company/qfilename首次匹配company后就退出sed程序只所以看sed命令,是因为我遇到了这个一个问题。网上有很多教程,他们发表了很多程序代码,但是作者为了解释方便,都对程序作了行号编码,就像下面这样:代码:1:#!/bin/bash2:#renamefileextesions3:#4:#rfeold_extensionsnew_extension假设这个文件名是tmp,那么我们可以使用下面的命令来去掉这个行号和冒号(:)代码:sed-es/0-91,:/gtmp不过上面的命令的命令有一个缺点,那就是如果这个行号不是数字开头,而是有空格的话,那就需要修改匹配规则,规则应该修改为匹配第一个非空白字符是数字开始,后面接一个冒号的配对。命令如下:代码:sed-es/0-9a-zA-Z*0-91,:/gtmp这令我很兴奋,于是想看看sed到底有多厉害,看了以后,明白的是不是sed有多厉害,就像awk一样,他们只是把正规表达式用到了极致。以Redhat6.0为测试环境事实上在solaris下的sed命令要比linux强,但因为没有测试环境,我这里只给在linux下经过测试的用法。命令行参数简介首先假设我们有这样一个文本文件sedtest.txt输出指定范围的行p在每一行前面增加一个制表符(I)在每一行后面增加-end显示指定模式匹配行的行号/pattern/=在匹配行后面增加文本/pattern/a或者addressa删除匹配行/pattern/d或者address1,address2d替换匹配行/pattern/c或者address1,address2c在匹配行前面插入文本/pattern/i或者addressi替换匹配串(注意不再是匹配行)addr1,addr2s/old/new/g限定范围后的模式匹配指定替换每一行中匹配的第几次出现&代表最后匹配利用sed修改PATH环境变量测试并提高sed命令运行效率指定输出文件address1,address2woutputfile指定输入文件addressrinputfile替换相应字符address1,address2y/old/new/!号的使用c正则表达式c的使用sed命令中正则表达式的复杂性转换man手册成普通文本格式(新)sed的man手册(用的就是上面的方法)命令行参数简介sed-escript指定sed编辑命令-fscriptfile指定的文件中是sed编辑命令-n寂静模式,抑制来自sed命令执行过程中的冗余输出信息,比如只显示那些被改变的行。不明白?不要紧,把这些肮脏丢到一边,跟我往下走,不过下面的介绍里不包括正则表达式的解释,如果你不明白,可能有点麻烦。首先假设我们有这样一个文本文件sedtest.txtcatsedtest.txtSedisastreameditor-Astreameditorisusedtoperformbasictexttransformationsonaninputstream-Whileinsomewayssimilartoaneditorwhichpermitsscriptededits(suchased),-sedworksbymakingonlyonepassovertheinput(s),andisconsequentlymore-efficient.Butitissedsabilitytofiltertextinapipelinewhichparticularly-输出指定范围的行pothertypesofeditors.sed-e1,4p-nsedtest.txtsed-e/from/p-nsedtest.txtsed-e1,/from/p-nsedtest.txt在每一行前面增加一个制表符(I)seds/I/gsedtest.txt注意I的输入方法是ctrl-vctrl-i单个表示行首在每一行后面增加-endseds/$/-end/gsedtest.txt单个$表示行尾显示指定模式匹配行的行号/pattern/=sed-e/is/=sedtest.txt1Sedisastreameditor-3Astreameditorisusedtoperformbasictexttransformationsonaninputstream-Whileinsomewayssimilartoaneditorwhichpermitsscriptededits(suchased),-7sedworksbymakingonlyonepassovertheinput(s),andisconsequentlymore-9efficient.Butitissedsabilitytofiltertextinapipelinewhichparticularly-意思是分析sedtest.txt,显示那些包含is串的匹配行的行号,注意11行中出现了is字符串这个输出是面向stdout的,如果不做重定向处理,则不影响原来的sedtest.txt在匹配行后面增加文本/pattern/a或者addressaDsed-fsedadd.scriptsedtest.txtSedisastreameditorAstreameditorisusedtoperformbasictexttransformationsonaninputstreamWhileinsomewayssimilartoaneditorwhichpermitsscriptededits(suchased),-sedworksbymakingonlyonepassovertheinput(s),andisconsequentlymore-efficient.Butitissedsabilitytofiltertextinapipelinewhichparticularly-scz/home/scz/srcsed-ea+-找到包含from字符串的行,在该行的下一行增加+。这个输出是面向stdout的,如果不做重定向处理,则不影响原来的sedtest.txt很多人想在命令行上直接完成这个操作而不是多一个sedadd.script,不幸的是,这需要用?nbsp;?nbsp;续行符,scz/home/scz/srcsed-e/from/a+sedtest.txtscz/home/scz/srcsed-ea+sedtest.txt上面这条命令将在所有行后增加一个新行+scz/home/scz/srcsed-e1a+sedtest.txt把下面这两行copy/paste到一个shell命令行上,效果一样+sedtest.txtaddressa只接受一个地址指定对于a命令,不支持单引号,只能用双引号,而对于d命令等其他命令,同时删除匹配行/pattern/d或者address1,address2dsed-e/-/dsedtest.txtSedisastreameditorAstreameditorisusedtoperformbasictexttransformationsonaninputstreamWhileinsomewayssimilartoaneditorwhichpermitsscriptededits(suchased),sedworksbymakingonlyonepassovertheinput(s),andisconsequentlymoreefficient.Butitissedsabilitytofiltertextinapipelinewhichparticularlysed-e6,10dsedtest.txt删除6-10行的内容,包括6和10sed-e2dsedtest.txt删除第2行的内容sed1,/$/dsedtest.txt删除从第一行到第一个空行之间的所有内容注意这个命令很容易带来意外的结果,当sedtest.txt中从第一行开始并没有空行,则sed删?nbsp;?nbsp;sed1,/from/dsedtest.txt删除从第一行到第一个包含from字符串的行之间的所有内容,包括第一个包含from字符串的行。替换匹配行/pattern/c或者address1,address2csed-e/is/c*sedtest.txt寻找所有包含is字符串的匹配行,替换成*-*-Whileinsomewayssimilartoaneditorwhichpermitsscriptededits(suchased),-*-*-sed-e1,11c*sedtest.txt-在1-12行内搜索所有from字符串,分别替换成*字符串限定范围后的模式匹配sed/But/s/is/are/gsedtest.txt对那些包含But字符串的行,把is替换成aresed/is/s/t/T/sedtest.txt对那些包含is字符串的行,把每行第一个出现的t替换成Tsed/While/,/from/psedtest.txt-n输出在这两个模式匹配行之间的所有内容指定替换每一行中匹配的第几次出现seds/is/are/5sedtest.txt把每行的is字符串的第5次出现替换成are&代表最后匹配seds/$/(&)/sedtest.txt给所有空行增加一对()seds/is/(&)/gsedtest.txt给所有is字符串外增加()seds/.*/(&)/sedtest.txt给所有行增加一对()sed/is/s/.*/(&)/sedtest.txt给所有包含is字符串的行增加一对()利用sed修改PATH环境变量先查看PATH环境变量scz/home/scz/srcecho$PATH/usr/bin:/usr/bin:/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/X11R6/bin:.去掉尾部的:/usr/X11R6/bin:.scz/home/scz/srcecho$PATH|seds/(.*):/usr/X11R6/bin:.$/1/usr/bin:/usr/bin:/bin:/usr/local/bin:/sbin:/usr/sbin去掉中间的:/bin:scz/home/scz/srcecho$PATH|seds/(.*):/bin:(.*)$/12/usr/bin:/usr/bin/usr/local/bin:/sbin:/usr/sbin:/usr/X11R6/bin:./表示/失去特殊意义/同样表示/失去意义1表示子匹配的第一次出现2表示子匹配的第二次出现(.*)表示子匹配去掉尾部的:,然后增加新的路径PATH=echo$PATH|seds/(.*):$/1/:$HOME/src注意反引号和单引号的区别。测试并提高sed命令运行效率timesed-n1,12pwebkeeper.db/dev/nulltimesed12qwebkeeper.db/dev/null可以看出后者比前者效率高。addressq当碰上指定行时退出sed执行指定输出文件address1,address2woutputfilesed1,10wsed.outsedtest.txt-n将sedtest.txt中1-10行的内容写到sed.out文件中。指定输入文件addressrinputfilesed1rsedappend.txtsedtest.txt将sedappend.txt中的内容附加到sedtest.txt文件的第一行之后替换相应字符address1,address2y/old/new/sedy/abcdef/ABCDEF/sedtest.txt将sedtest.txt中所有的abcdef小写字母替换成ABCDEF大写字母。!号的使用sed-e3,7!dsedtest.txt删除3-7行之外的所有行sed-e1,/from/!dsedtest.txt找到包含from字符串的行,删除其后的所有行c正则表达式c的使用sed-e:from:dsedtest.txt等价于sed-e/from/dsedtest.txtsed命令中正则表达式的复杂性catsedtest.txt/.*($)D如何才能把该行替换成($)/.*转换man手册成普通文本格式(新)mansed|col-bsed.txtsed-es/H/g-e/$/d-es/I/g-es/I/gsed.txtsedmantxt删除所有退格键、空行,把行首的制表符替换成8个空格,其余制表符替换成一个空格。sed的man手册(用的就是上面的方法)NAMEsed-aStreamEDitorSYNOPSISsed-n-V-quiet-silent-version-help-escript-expression=script-fscript-file-file=script-filescript-if-no-other-scriptfile.DEscriptIONSedisastreameditor.Astreameditorisusedtoper-formbasictexttransformationsonaninputstream(afileorinputfromapipeline).Whileinsomewayssimilartoaneditorwhichpermitsscriptededits(suchased),sedworksbymakingonlyonepassovertheinput(s),andisconsequentlymoreefficient.Butitissedsabilitytofiltertextinapipelinewhichparticularlydistinguishesitfromothertypesofeditors.OPTIONSSedmaybeinvokedwiththefollowingcommand-lineoptions:-V-versionPrintouttheversionofsedthatisbeingrunandacopyrightnotice,thenexit.-h-helpPrintausagemessagebrieflysummarizingthesecommand-lineoptionsandthebug-reportingaddress,thenexit.-n-quiet-silentBydefault,sedwillprintoutthepatternspaceattheendofeachcyclethroughthescript.Theseoptionsdisablethisautomaticprinting,andsedwillonlyproduceoutputwhenexplicitlytoldtoviathepcommand.-escript-expression=scriptAddthecommandsinscripttothesetofcommandstoberunwhileprocessingtheinput.-fscript-file-file=script-fileAddthecommandscontainedinthefilescript-filetothesetofcommandstoberunwhileprocessingtheinput.Ifno-e,-f,-expression,or-fileoptionsaregivenonthecommand-line,thenthefirstnon-optionargumentonthecommandlineistakentobethescripttobeexecuted.Ifanycommand-lineparametersremainafterprocessingtheabove,theseparametersareinterpretedasthenamesofinputfilestobeprocessed.Afilenameof-referstothestandardinputstream.Thestandardinputwillpro-cessedifnofilenamesarespecified.CommandSynopsisThisisjustabriefsynopsisofsedcommandstoserveasaremindertothosewhoalreadyknowsed;otherdocumenta-tion(suchasthetexinfodocument)mustbeconsultedforfullerdescriptions.Zero-addresscommands:labelLabelforbandtcommands.#commentThecommentextendsuntilthenextnewline(ortheendofa-escriptfragment).Theclosingbracketofablock.Zero-orOne-addresscommands=Printthecurrentlinenumber.atextAppendtext,whichhaseachembeddednewlinepre-ceededbyabackslash.itextInserttext,whichhaseachembeddednewlinepre-ceededbyabackslash.qImmediatelyquitthesedscriptwithoutprocessinganymoreinput,exceptthatifauto-printisnotdiabledthecurrentpatternspacewillbeprinted.rfilenameAppendtextreadfromfilename.CommandswhichacceptaddressrangesBeginablockofcommands(endwitha).blabelBranchtolabel;iflabelisomitted,branchtoendofscript.tlabelIfas/hasdoneasuccessfulsubstitutionsincethelastinputlinewasreadandsincethelasttcommand,thenbranchtolabel;iflabelisomitted,branchtoendofscript.ctextReplacetheselectedlineswithtext,whichhaseachembeddednewlinepreceededbyabackslash.dDeletepatternspace.Startnextcycle.DDeleteuptothefirstembeddednewlineinthepat-ternspace.Startnextcycle,butskipreadingfromtheinputifthereisstilldatainthepat-ternspace.hHCopy/appendpatternspacetoholdspace.gGCopy/appendholdspacetopatternspace.xExchangethecontentsoftheholdandpatternspaces.lListoutthecurrentlineinavisuallyunambigu-ousform.nNRead/appendthenextlineofinputintothepatternspace.pPrintthecurrentpatternspace.PPrintuptothefirstembeddednewlineofthecur-rentpatternspace.s/regexp/replacement/Attempttomatchregexpagainstthepatternspace.Ifsuccessful,replacethatportionmatchedwithreplacement.Thereplacementmaycontainthespe-cialcharacter&torefertothatportionofthepatternspacewhichmatched,andthespecialescapes1through9torefertothecorrespondingmatchingsub-expressionsintheregexp.wfilenameWritethecurrentpatternspacetofile-name.y/source/dest/Transliteratethecharactersinthepatternspacewhichappearinsourcetothecorrespondingcharac-terindest.AddressesSedcommandscanbegivenwithnoaddresses,inwhichcasethecommandwillbeexecutedforallinputlines;withoneaddress,inwhichcasethecommandwillonlybeexecutedforinputlineswhichmatchthataddress;orwithtwoaddresses,inwhichcasethecommandwillbeexecutedforallinputlineswhichmatchtheinclusiverangeoflinesstartingfromthefirstaddressandcontinuingtothesec-ondaddress.Threethingstonoteaboutaddressranges:thesyntaxisaddr1,addr2(i.e.,theaddressesaresepa-ratedbyacomma);thelinewhichaddr1matchedwillalwaysbeaccepted,evenifaddr2selectsanearlierline;andifaddr2isaregexp,itwillnotbetestedagainstthelinethataddr1matched.Aftertheaddress(oraddress-range),andbeforethecom-mand,a!maybeinserted,whichspecifiesthatthecom-mandshallonlybeexecutediftheaddress(oraddress-range)doesnotmatch.Thefollowingaddresstypesaresupported:numberMatchonlythespecifiedlinenumber.firststepMatcheverystepthlinestartingwithlinefirst.Forexample,sed-n12pwillprintalltheodd-numberedlinesintheinputstream,andtheaddress25willmatcheveryfifthline,startingwiththesecond.(ThisisaGNUextension.)$Matchthelastline./regexp/Matchlinesmatchingtheregularexpressionregexp.cregexpcMatchlinesmatchingtheregularexpressionregexp.Thecmaybeanycharacter.RegularexpressionsPOSIX.2BREsshouldbesupported,buttheyarentcom-pletelyyet.Thensequenceinaregularexpressionmatchesthenewlinecharacter.TherearealsosomeGNUextensions.XXXFIXME:moreneedstobesaid.Attheveryleast,areferencetoanotherdocumentwhichdescribeswhatissupportedshouldbegiven.MiscellaneousnotesThisversionofsedsupportsasequenceinallregularexpressions,thereplacementpartofasubstitute(s)command,andinthesourceanddestpartsofatransliterate(y)command.Theisstripped,andthenewlineiskept.SEEALSOawk(1),ed(1),expr(1),emacs(1),perl(1),tr(1),vi(1),regex(5)well,oneoughttobewritten.XXX,,anyofvariousbooksonsed,thesedFAQ(http:/www.wollery.demon.co.uk/sedtut10.txt,/sed/sedfaq.htm).BUGSE-.BesuretoincludethewordsedsomewhereintheSubject:field.Sed学习笔记-TableofContents1.Sed简介2.定址3.Sed命令4.选项5.元字符集6.实例7.脚本1.Sed简介sed是一种在线编辑器,它一次处理一行内容。处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(patternspace),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。接着处理下一行,这样不断重复,直到文件末尾。文件内容并没有改变,除非你使用重定向存储输出。Sed主要用来自动编辑一个或多个文件;简化对文件的反复操作;编写转换程序等。以下介绍的是Gnu版本的Sed3.02。2.定址可以通过定址来定位你所希望编辑的行,该地址用数字构成,用逗号分隔的两个行数表示以这两行为起止的行的范围(包括行数表示的那两行)。如1,3表示1,2,3行,美元符号($)表示最后一行。范围可以通过数据,正则表达式或者二者结合的方式确定。3.Sed命令调用sed命令有两种形式:sedoptionscommandfile(s)sedoptions-fscriptfilefile(s)a在当前行后面加入一行文本。blable分支到脚本中带有标记的地方,如果分支不存在则分支到脚本的末尾。c用新的文本改变本行的文本。d从模板块(Patternspace)位置删除行。D删除模板块的第一行。i在当前行上面插入文本。h拷贝模板块的内容到内存中的缓冲区。H追加模板块的内容到内存中的缓冲区g获得内存缓冲区的内容,并替代当前模板块中的文本。G获得内存缓冲区的内容,并追加到当前模板块文本的后面。l列表不能打印字符的清单。n读取下一个输入行,用下一个命令处理新的行而不是用第一个命令。N追加下一个输入行到模板块后面并在二者间嵌入一个新行,改变当前行号码。p打印模板块的行。P(大写)打印模板块的第一行。q退出Sed。rfile从file中读行。tlabelif分支,从最后一行开始,条件一旦满足或者T,t命令,将导致分支到带有标号的命令处,或者到脚本的末尾。Tlabel错误分支,从最后一行开始,一旦发生错误或者T,t命令,将导致分支到带有标号的命令处,或者到脚本的末尾。wfile写并追加模板块到file末尾。Wfile写并追加模板块的第一行到file末尾。!表示后面的命令对所有没有被选定的行发生作用。s/re/string用string替换正则表达式re。=打印当前行号码

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论