Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I use the grep command to search for a string in many files. Is there something similar to "search and replace"?

share|improve this question
up vote 16 down vote accepted

You are looking for the sed command. For example, to replace the "dog" with "cat" in all text files in the current directory:

sed -i 's/dog/cat/' *.txt
share|improve this answer
1  
Simple and nice. – Luis Alvarado Feb 2 '12 at 14:29

sed comes to mind. Example:

sed s/cat/dog/ <input >output

This searches for cat in a line and puts dog on it's place in the file input and writes to file output.

share|improve this answer

sed is the right tool; but, as an alternative, you can even use ex commands in vim:

vim -c 'args <files> | argdo %s/cat/dog/g | x'

where <files> is the list of files or patterns in which you want to make the substitution.

share|improve this answer
    
note argdo is not POSIX pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html – Steven Penny Apr 17 at 0:40

You can use Vim in Ex mode:

for b in *.txt
do
  ex -sc '%s/OLD/NEW/g|x' "$b"
done
  1. % select all lines

  2. s substitute

  3. g replace all instances in each line

  4. x save and close

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.