Monday, June 1, 2009

How to edit (find-and-replace) in a file without opening it?

I needed to edit couple of files in a directory in order to find and replace one name/string with another one. Here is what I did using vi:


$cat test_file
This is a test file.
Today is Monday.

$vi -c "%s/Monday/Tuesday/g|wq" test_file
"test_file" 2 lines, 38 characters "test_file" 2 lines, 39 characters

$cat test_file
This is a test file.
Today is Tuesday.
$


This trick can be even used in shell scripts to edit large number of files at the same time. Enjoy!!!

No comments: