LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Can I use GREP to find & replace text? (https://www.linuxquestions.org/questions/linux-newbie-8/can-i-use-grep-to-find-and-replace-text-656738/)

jim.thornton 07-18-2008 06:13 PM

Can I use GREP to find & replace text?
 
Hello,

I have just changed a setting and I need to go through about 30 files within a directory and find all instances of a word, and change it to another word.

My intial though was GREP was the tool to use, however, I looked in the man pages and I can't find a "find & replace" option within it.

Is there a way that I can use grep to look into every file within the directory and change the word?

any help is greatly appreciated.

Mr. C. 07-18-2008 06:25 PM

Nope. Use sed, awk, perl, ed.

custangro 07-18-2008 06:32 PM

Quote:

Originally Posted by jim.thornton (Post 3219379)
Hello,

I have just changed a setting and I need to go through about 30 files within a directory and find all instances of a word, and change it to another word.

My intial though was GREP was the tool to use, however, I looked in the man pages and I can't find a "find & replace" option within it.

Is there a way that I can use grep to look into every file within the directory and change the word?

any help is greatly appreciated.

I dunno maybe...(note...that's a number one...on an l)

Code:

for i in $(ls -1 /path/to/dir)
do
  sed -e 's/old/new/g' /path/to/dir/$i > /path/to/dir/$i.new
done

There is probably a better way but I'm too lazy to think...I mean...comeon...it's friday! :D

-C

pixellany 07-18-2008 06:36 PM

simple search and replace is easily done with SED.

Example:
sed 's/was/is/g' filename > newfilename

This finds all occurences of "was" and replaces them with "is". The issue is that is will find "was" even if it is part of a word. To restrict the search to whole words, use the regex for word boundaries: \<\>
sed 's/\<was\>/is/g' filename > newfilename

To edit a file in place:
sed -1 's/\<was\>/is/g' filename

To edit multiple files--all in the same directory:
for file in `ls`; do
sed 's/\<was\>/is/g' filename
done


All times are GMT -5. The time now is 04:48 AM.