Wednesday 11 December 2013

Sed utility

Sed quick learn for general editing and use.
This is just a quick reference form myself and others who don't use it regularly.

Sed is one more editing utility inspired from ed command. Script ed is what it basically is.
ed edits a line at a time while sed edits all line in general it is a global.
sed [-e] 'instruction' file
 were -e is option is important when you are suppling multiple instruction.
 
example let a file contain a list of address and cities name in short form
then following:
sed 's/MA/Massachusetts/' list
where list is file containing address list.
In this as you can see that the instruction is   are similar to that you give in ed.
 but you see that you don't have to provide address(not the addresses in list it mean position or line number in the file) to lines as in ed. It simply traverses to all lines one by one. also it will print out the output.

two ways to specify multiple instruction
1st: Using a ';'

like
 sed 's/MA/Massachusatts/ ; s/PA/Pennsylvania/ ' list

2nd: Using -e

sed -e 's/MA/Massachusatts/' -e 's/PA/Pennsylvania/ ' list

or 
3rd: using multiline entery capability

sed '
s/MA/Massachusetts/
s/PA/Pennsylvania/' list

Ok thats it to entering commands

Now how to use script file as an input to sed?
script file can be like this
suppose  sedscr is a script file then
cat sedscr
s/MA/Massachusetts/
s/PA/Pennsylvania/

 and you can use it as

sed -f sedscr list

as sed directly print it to default output or terminal one can rather redirect it and store the modified out put in a file.
as
 sed -f sedscr list > newlist

you can suppress the printing on screen of all the line by using '-n' option
as
sed -n -e 's/MA/Massachusetts/' list
this will not give or display any out put
if you want to view just the modified lines use 'p' as in ed command
as
sed -n -e 's/MA/Massachusetts/p' list

Thats it for sed
look for further learning on :http://www.grymoire.com/Unix/Sed.html

No comments:

Post a Comment