2009-02-26

bash - search & replace in a file using sed

Traditionally, search and replace in files have to be done in editor. But if the operation involves multiple files, it would not be practical to use editor on every files as it can be tedious (more then 5 files?) and also error prune. By using a few of bash utilities, the task can be achieve with no error and also a great opportunity to learn a few handy bash tools / command. Below is a scenario that commonly needs to be done.

Problem :
Find & replace text from a set of files


Solution :
use sed with parameter -i


e.g.
sed -i .bak 's/text-to-search/text-to-replace/g' *.txt

It will replace every word of "text-to-search" with "text-to-replace" in all files in the directory with the extension of txt and backup the original file with extension .bak .

Hasta la vista !!!

No comments: