Re: [SLUG] Global Search and Replace

From: blee2@tampabay.rr.com
Date: Fri Jan 05 2007 - 19:42:00 EST


Thus Paul M Foster hast written on Thu, Jan 04, 2007 at 04:16:54PM -0500, and, according to prophecy, it shall come to pass that:
> Anyone know of a nifty tool which will do a global search and replace of
> text inside a bunch of files, all at once?

I use sed. The syntax is the same as the perl example:

        sed -e 's/string1/replacement/g' infile

You'll probably want to run this sed with a for loop:

        for i in *.txt
        do
                sed -e 's/worker/slave/g' $i > $i.new
        done

For future reference, to do this IN vi:

        :%s/string1/replacement/g

(Yes, that is "%s/".)

and to delete all lines containing a certain string:

        :g/string/d

It took me a long time to find that last one.

The "s/" in these commands is "substitute", the "g/" is "grep" and the "d" is to delete the line.

You can also use "y/" ("Yubstitute") to replace individual characters.
For example:

        sed -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' file1

will capitalize all letters, but

        sed -e 'y/trzAGW/RTZagw/' file1

will capitalize "R", "T" and "Z" and lowercase "A", "G" and "W", and

        sed -e 'y/.+-A/!-+f/' file1

should replace "." with "!", "+" with "-", "-" with "+", and "A" with "f"

-----------------------------------------------------------------------
This list is provided as an unmoderated internet service by Networked
Knowledge Systems (NKS). Views and opinions expressed in messages
posted are those of the author and do not necessarily reflect the
official policy or position of NKS or any of its employees.



This archive was generated by hypermail 2.1.3 : Fri Aug 01 2014 - 20:28:45 EDT