Making global changes with sed

Another handy command you can use is sed, which lets you make multiple changes to files, without ever opening an editor. For example, as a new Webmaster, you might use sed to change all occurrences of the previous Webmaster's e-mail address to your own, as shown in our example below. As we'll show in this section, you can use sed to make global changes within documents.

To make global changes with sed:

  • sed /[email protected] 
    → /[email protected]/g address.htm 
    → > address.htm

    Type sed, followed by

    • /the text you want to replace (/[email protected])

    • A slash (/)

    • The replacement text ([email protected])

    • Another /

    • g, which tells UNIX to apply the change globally. (If you omit the g, only the first occurrence on each line will be changed.)

    • The name of the file in which the changes should be made (address.htm).

    You can redirect the output to the same file name (as we did here; see Code Listing 6.10), redirect it to a new one, or pipe it to another command entirely.

Tip

You can have sed zip through multiple documents. See Chapter 10 for information on how to make a shell script with a loop.


Tip

Because sed commands can be long and unwieldy, it might be helpful to save the commands in a separate text file (so you don't have to retype them). For example, if you saved the command s/[email protected]/newaddr@ray comm.com/g in a file called script.sed, you could issue sed -f script.sed address.htm > address.htm to run the sed commands from the script.sed file.


Code Listing 6.10. You can use sed to make changes throughout files, such as the address change here.
[ejr@hobbes manipulate]$ sed
   s/[email protected]/[email protected]
   /g address.htm > address.htm
[ejr@hobbes manipulate]$ head address.htm


<BODY BACKGROUND="/images/background.gif"
 BGCOLOR="#FFFFFF" TEXT="#000000" LINK=
"#009900" VLINK="#000000" ALINK="#ff0000">

<P>
Please send all comments to <A
  HREF="mailto:[email protected]">newaddr@r
  aycomm
.com</A>.
</P>

<TABLE BORDER=0>
<TR>
<TD WIDTH="150" VALIGN=TOP>
[ejr@hobbes manipulate]$

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.238.70