11

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

4 Answers 4

19

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
1
1

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.

0
1

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.

1
0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .