Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev
Chapter 7: awk Revisited
Next

How to write sed scripts?

Sed command can be grouped together in one text file, this is know as sed script. For next example of sed script create inven1 data file and create "chg1.sed", script file as follows

Tip: Give .sed extension to sed script, .sh to Shell script and .awk to awk script file(s), this will help you to identify files quickly.

$ cat > chg1.sed
1i\
Price of all items changes from 1st-April-2001
/Pen/s/20.00/19.5/
/Pencil/s/2.00/2.60/
/Rubber/s/3.50/4.25/
/Cock/s/45.50/51.00/

Run the above sed script as follows:
$ sed -f chg1.sed inven1
Price of all items changes from 1st-April-2001
1. Pen 5 19.5
2. Pencil 10 2.60
3. Rubber 3 4.25
4. Cock 2 51.00

In above sed script, the 1i\ is the (i) insert command. General Syntax is as follows:
Syntax:
[line-address]i\
text

So,
1i\
Price of all items changes from 1st-April-2001

means insert the text "Price of all items changes from 1st-April-2001" at line number 1.

Same way you can use append (a) or change (c) command in your sed script,
General Syntax of append
Syntax:
[line-address]a\
text

Example:
/INDIA/ a\
E-mail: vg@indiamail.co.in

Find the word INDIA and append (a) "E-mail: vg@indiamail.co.in" text.

General Syntax of change as follows:
Syntax:
[line-address]c\
text

Example:
/INDIA/ c\
E-mail: vg@indiamail.co.in

Find the word INDIA and change e-mail id to "vg@indiamail.co.in"

Rest of the statements (like /Pen/s/20.00/19.5/) are general substitute statements.


Prev
Home
Next
Redirecting the output of sed command
Up
More examples of sed