您的位置:首页 > 运维架构 > Linux

linux命令分析---SED (一)

2012-06-24 14:20 218 查看
本文转自http://maketecheasier.com/beginners-guide-to-sed-linux/2012/03/29

Aftergrep,thenextlogicalstepisatutorialonsed.ThesedcommandcomesfromStreamEDitor,andasitsnameindicates,itdealswithtextflux.However,ifsedisoneofthemostpowerfulcommandsinUnix,itsmanualpageisalsoamongthemostenigmatic.Iwilltryinthisarticletosummarizethemostbasicusageofsedandthengiveyouafewexamplesofadvancedscripts.

Basics

Thegeneralcommandforsedissomethinglike:

sed[option]'{script}'[textfile]

Sedwillperformtheoperationsthatyouwanthimtodoonthetextfileanddisplaytheresultinthestandardoutput.Ifyouwanttheresultinatextfile,youcaneitherredirectitviathehabitualmethod:

sed[option]'{script}'[textfile]>[editedtextfile]


Orusetheoption“
-i
”thatwilldirectlyedittheinputfile:

sed-i[option]'{script}'[textfile]


Nowlet’sbeginworkingonthescript.Themostobviousfirststepisthenullscript:

sed''test.txt


willjustdisplaythetextintest.txt.



Agoodusageofsedisdeletion.Let’spracticethroughexamples.

sed'2,4d'test.txt


willdeletethelines2to4oftest.txt.



Youcanguessthatthesyntaxforthescriptis:

sed'[firstlinetodelete][lastlinetodelete]d'test.txt


Butthefancypartcomeswhenyouuseregularexpressions,orregex,asdelimiterforthedeletion.Forexample,

sed'/^#/d'test.txt


willdeleteeverylinethatbeginswith“#”(inotherwords,ifyoucode,itwilldeleteallyourcomments).



Thegeneralsyntaxis

sed'/regex/d'test.txt


fordeletingthelinecontainingtheregex.

sed'/regex1/,/regex2/d'test.txt


fordeletingtheintervalfromthelinecontainingregex1tothelinecontainingregex2.

Thespecialcharacter“^”thatIusedinthefirstexampleistoindicatethebeginningoftheline.

Then,thesecondbasicusagethatIcanthinkofissubstitution.Thegeneralsyntaxis:

sed-re's/regex1/regex2/'test.txt


Itwillhaveforeffecttosearchinthefirstlineforregex1,replaceitwithregex2,gotothenextlineandrepeatuntiltheendoftheentryflux.

Agoodexampleis:

sed-re's/^#*//'test.txt




Itwillreplacethesymbol“#”atthebeginningofaline,andalltheblankspaceswithnothing.Inotherterms,ituncommentsthetextfile.Thesymbol“*”isameta-characterdesigning0ormoreblankspaceshere.

Advanced

Youcandosomeprettyfancystuffwithsed,butyouwillreachthelimitprettyfastifyoudon’tpayattentiontoitsbasicbehavior.Seddealswithfluxlinearly:Itappliesaline-by-linetreatmenttoatextfile.Ifyouwanttodomorethanonemodificationtoasameline,youhavetouselabelsandmulti-linetreatment.Allofthiscanbecomeverycomplex,veryquickly.Iwillnowshowyouafewadvancedexamplesandexplainthemtoyou.Ifyouwantmore,IamsurethatyoucansearchbyyourselfandusethebasicsIgaveyou.

Ifyouwanttodeletetheemptylinesofafile,youcanusethecommand

sed-re'/^$/{N;D}'test.txt


Themeta-character“$”meanstheendoftheline,so“^$”designsanemptyline.Then,“{N;D}”isarathercomplexsyntaxforsayingdeletethatline.

Ifyouwanttodeleteeverytaginahtmlfile,thisisthecommandforyou:

sed-re':starts/<[^>]*>//g;/</{N;bstart}'test.txt


The“:start”iscalledalabel.Itisabitlikeatagwithinthescriptthatwewanttogobacktolaterinordertoapplymultiplechangestoasameline.sedsearchesforanythingoftheform“<XXX>”(theregex<[^>]*>)andreplacesitwithnothing,sothefirsthtmltagofthelineisdeleted.Butthen,beforegoingtothenextline,itchecksifthereissomethingelsebeginningwith“<”,andifthereis,itgoesbacktothelabel“:start”andre-appliesthetreatment.

Conclusion

Youarenowreadytostudymoredeeplysed,orjustuseitforsimplemodifications.ItisacommandthatIfindparticularlyusefulinscriptsingeneral,butittookmesometimetounderstanditssyntax.Ihopeitwillbemuchfasterforyou.

Doyouknowanotherbasiccommandforsed?Ordoyouuseanotheradvancedscriptinvolvingsedthatyouwanttoshare?Pleaseletusknowinthecomments.


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: