Making Global Changes with sed


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 email address to your own. As we'll show in this section, you can use sed to make global changes within documents.

Code Listing 6.10. You can use sed to make changes throughout files, such as the address change here.

[ejr@hobbes manipulate]$ sed 's/oldaddr@raycomm.com/newaddr@  raycomm.com /g  address.htm > address-new.htm [ejr@hobbesmanipulate]$ head  address-new.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:newaddr@raycomm.com>  newaddr@raycomm.com</A>. </P> <TABLE BORDER=0> <TR> <TD WIDTH="150" VALIGN=TOP> [ejr@hobbes manipulate]$ 

To make global changes with sed:

  • sed 's/oldaddr@raycomm.com  /newaddr@raycomm.com /g address.htm  > address-new.htm 

    Type sed, followed by

    • A single quote (' )

    • A leading "s"

    • A slash (/)

    • The text you want to replace

      (oldaddr@raycomm.com)

    • Another slash (/)

    • The replacement text (newaddr@raycomm.com/g)

    • Another single quote (')

    • Yet another /

    • g, which tells sed 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 a new filename (see Code Listing 6.10) or pipe it to another command entirely. You cannot redirect to the same filename or you'll end up with no content in your file.

Tips

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

  • 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/oldaddr@ raycomm.com/newaddr@raycomm.com/g in a file called script.sed, you could issue sed -f script.sed address.htm > address-new.htm to run the sed commands from the script.sed file. You can have as many commands as you want in your script.sed file.





Unix(c) Visual Quickstart Guide
UNIX, Third Edition
ISBN: 0321442458
EAN: 2147483647
Year: 2006
Pages: 251

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net