Saturday, October 20, 2012

SED (Stream Editor)

Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline).The Contents of the file will not be altered.

An Example would be

sed ‘s/string1/string2/g’ inputFile > outputFile

A Few more Examples are

sed -n '404,480p' sample :Print Lines Between 404 and 487 : 

sed ’404,480d’ sample : Pint Every Thing Except from 404 to 480 :

sed -e '1d' sample : Remove the First List in the sample File  ( Similarly Other Lines too )

sed -e '2,4d' sample : Remove Lines from 2 to 4

sed -n -e '/Great/,/task/p' sample : Print Lines Between 'Great' and 'task' from Sample File

sed -e 's/also/plso/g' sample : Replace 'also' with 'plso' globally

sed -e '2,4s/also/plso/g' sample : Replace 'also' with 'plso' in between lines 2 and 4

sed '/Dragon/G' sample : Add a Balnk Line under the line where the regular expression Dragon is found

sed '/Dragon/{x;p;x;G;}' sample : Add a Balnk Line Above and under the line where the regular expression Dragon is found

sed -n '$=' sample   : Count Lines

sed 's/^[ \t]*//' sample : Remove the Blank Lines From the File and Left allign

sed -e '/but/!s/also/pslo/g' sample : Replace all lines which contain also to plso but leave lines that contain but

sed -e 's/also/plso/g;s/but/nut/g' sample : replace also with plso and but with nut

sed 10g sample : first 10 lines

sed q sample : First Line

sed '$!d' sample : print the Last Line

sed -n '$p' sample : Last Line

sed -n '8,12p' sample : print lines from 8 to 12

sed -n '52p' sample : print Line Number 52

sed '3 s/Great/Treat/g' sample : Search and replace only in 3 Line

sed ‘1,4  s/Great/Treat/g' sample : Search and Replace only from 1 to 4 lines

sed -f script.sed sample : Write all the commands in Script.sed and exetute them

sed '5!s/also/plso/' sample : replace also with plso leaving 5 line

sed '1~3d' sample : Delete every 3 line starting from 1

sed '/pattern/d' sample : Delete line when Matched

sed 's/unix/linux/' sample| sed 's/os/system/'  : Multiple Sed Commands . Piping the Output

sed '3 s/unix/linux/' sample : Replace the String On Specific Line

sed 'p' sample : Diplicate the Lines

sed '/unix/ a "Add a new line"' sample : add a Line after you find a Match

sed '/unix/ i "Add a new line"' sample : Add a Line Before a Match

sed '/unix/ c "Change line"' sample : change a Line

sed 'y/ul/UL/' sample : transform the Text

sed -e '/^$/d' sample : Fileter Out Empty Lines

cat sample | sed -e 's/$/ mycomputer/' > sample : Add the computer named mycomputer to the end of every line in file

Many more To Come ,Keep Looking