Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer

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
add comment

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.