Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How can I replace a string in a file(s)?

Replacing strings in files based on certain search criteria is a very common task. How can I

replace string foo with bar in all files in the current directory?
do the same recursively for subdirectories?
replace only if the file name matches another string?
replace only if the string is found in a certain context?
replace if the string is on a certain line number?
replace multiple strings with the same replacement
replace multiple strings with different replacements
by

2 Answers

rahul07
You could also use find and sed, but I find that this little line of perl works nicely.

perl -pi -w -e 's/search/replace/g;' *.php

-e means execute the following line of code.
-i means edit in-place
-w write warnings
-p loop over the input file, printing each line after the script is applied to it.
My best results come from using perl and grep (to ensure that file have the search expression )

perl -pi -w -e 's/search/replace/g;' $( grep -rl 'search' )
pankajshivnani123
From a user's perspective, a nice & simple Unix tool that does the job perfectly is qsubst. For example,

% qsubst foo bar .c .h
will replace foo with bar in all my C files. A nice feature is that qsubst will do a query-replace, i.e., it will show me each occurrence of foo and ask whether I want to replace it or not. [You can replace unconditionally (no asking) with -go option, and there are other options, e.g., -w if you only want to replace foo when it is a whole word.]

How to get it: qsubst was invented by der Mouse (from McGill) and posted to comp.unix.sources 11(7) in Aug. 1987. Updated versions exist. For example, the NetBSD version qsubst.c,v 1.8 2004/11/01 compiles and runs perfectly on my mac.

Login / Signup to Answer the Question.