Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

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

What's the command line equivalent of: For every file that contains "AAA" within its contents, find "BBB" and replace it with "CCC"

Thus, the command would match and replace BBB in a file:

<html>
<head></head>
<body>
AAA
Hello world!
BBB    
</body>
</html>

But Not in a file:

<html>
<head></head>
<body>
Don't match me!
BBB    
</body>
</html>

Thanks in advance!

share|improve this question
up vote 1 down vote accepted

Try something like:

grep -Rl AAA . | xargs sed -i -e 's/BBB/CCC/'
share|improve this answer
    
Could you please explain what this actually does/means? It looks like it worked for the question asker, but for anyone else who finds this post later, what does this actually do? – nhinkle Feb 14 '11 at 9:41
    
Sure. grep -R PATTERN DIR means grep all files in DIR, recursively. Normally it prints the lines that match PATTERN, but the -l option means only print matching filenames... – Mikel Feb 14 '11 at 9:45
    
So the first half is printing out a list of files that contain AAA. Then we use xargs to do something with each file. In this case, run sed, replacing the first occurrence of BBB with CCC. If all occurrences need to be replaced, put a g after the last /. – Mikel Feb 14 '11 at 9:49

You must log in to answer this question.

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