home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.unix.questions
- Path: sparky!uunet!stanford.edu!leland.Stanford.EDU!dkeisen
- From: dkeisen@leland.Stanford.EDU (Dave Eisen)
- Subject: Re: how to search/replace over an entire directory
- Message-ID: <1992Nov16.022048.27425@leland.Stanford.EDU>
- Sender: news@leland.Stanford.EDU (Mr News)
- Organization: Sequoia Peripherals, Inc.
- References: <SCOTTH.92Nov14103759@kuwait.gdfwc3>
- Distribution: comp.unix.questions
- Date: Mon, 16 Nov 92 02:20:48 GMT
- Lines: 69
-
- Email bounced. Pardon me for posting something that is not really
- clean enough for general consumption.
-
- gdfwc3!kuwait!scotth@uunet.uu.net writes:
- >Is there an easy way to do a search and replace of a string over an
- >entire directory or a list of files. It would be nice it was something
- >like like
- >
- >$ search_replace -search string1 -replace string2 -directory this_directory
-
- This should work. I changed the usage to
-
- search_replace string1 string2 this_directory
-
- because as far as I could see, the -search, -replace, -directory
- weren't buying you anything. It would be easy enough to adjust.
-
- And I also am assuming that none of the arguments has any
- spaces in it or any characters (such as .) that have special
- meaning as regular expressions. All of this could be dealt
- with by quoting things appropriately, but this is just a
- quick off-the-top-of-my-head solution.
-
- I also assume your system supports the #! syntax for launching
- scripts. If not, figure out some other way to get /bin/sh
- to interpret this.
-
- Put this into a file and execute it as
-
- filename string1 string2 this_directory
-
- #! /bin/sh
-
- [ $# -eq 3 ] || {
- echo "Usage: $0 srchstring replstring dirname" >&2
- exit 1
- }
-
- srch=$1
- repl=$2
- dname=$3
-
- find $dname -type f -print |
- while read fname
- do
- ed - $fname <<-EOF
- 1,\$s/$srch/$repl/g
- w
- q
- done
-
- exit 0
-
-
- I tested it out and it worked, but I do tend to make mistakes when
- using ed, especially when I don't have my docs at hand. I'd test it
- before unleashing it on real data.
-
- If you have any questions about how either of this script works or
- about how to improve it to add better error checking or more flexibility,
- feel free to drop me a note. Shell programming can be tricky.
-
-
-
- --
- Dave Eisen Sequoia Peripherals: (415) 967-5644
- dkeisen@leland.Stanford.EDU Home: (415) 321-5154
- There's something in my library to offend everybody.
- --- Washington Coalition Against Censorship
-