File Exchange

image thumbnail

Find and Replace in Files

version (3.79 KB) by Tucker McClure
Replace the specified text in a list of files with new text.


Updated 01 Sep 2016

View Version History

View License

This utility will replace all string matches in the target files with a given string. This is similar to 'Replace all' in the editor, except that it can be used programmatically and on multiple files.
For instance, to replace all occurrences of 'abs' with 'mag':

>> find_and_replace('my_file.m', 'abs', 'mag')

Both the "match" and "replace" inputs can be regular expressions. For instance, we can replace all calls to sqrt(...) with my_sqrt(...), keeping the function's argument by using regular expressions.

>> find_and_replace(file_names, 'sqrt\((.*?)\)', 'my_sqrt\($1\)');

For more examples:

>> help find_and_replace;

Some knowledge of regular expressions is helpful, but not required, to use this tool. See 'Regular Expressions' in MATLAB's documentation.

Cite As

Tucker McClure (2021). Find and Replace in Files (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (22)

Ido Imanuel

Added in a hacked 'mock' option - so you can see the lines that are about to be edited. The return values is non-empty only when the mock==1 flag is passed. Please note: This code *DOES NOT* work with unicode characters - sometimes these are used in the comments to reference names of article writers, for example.

function [matches ] = find_and_replace(file, expression, replacement,mock)
% find_and_replace(file, to_find, to_replace)
% USAGE: find_and_replace(get_repo(),'uniform_clr\((.*?)\)','uniclr\($1\)',1)
% Replaces a string (expression) in a given file (file) with a new string
% (replacement).
@@ -51,7 +53,7 @@ function find_and_replace(file, expression, replacement,mock)

% For all files in the cell array...
matches = {};
n_tgtf = 0;
for k = 1:length(file)

% Make sure the file exists.
@@ -61,22 +63,38 @@ function find_and_replace(file, expression, replacement,mock)
'use regexprep.']);

% Read in the file as binary and convert to chars.
fid = fopen(file{k});
text = fread(fid, inf, '*char')';

if mock
c = regexp(text,expression,'forceCellOutput');
matches{k,1} = file{k};
matches{k,2} = c{:};
lines = {};
fid = fopen(file{k}); found = 0; ln = 1;
tline = fgetl(fid);
while ischar(tline)
c = regexp({tline},expression);
if ~isempty(c{:})
found = found+1;
lines{found,1} = ln;
lines{found,2} = tline;
tline = fgetl(fid);ln = ln+1;
if ~isempty(lines)
n_tgtf = n_tgtf+1;
matches{n_tgtf,1} = file{k};
matches{n_tgtf,2} = lines;
% Read in the file as binary and convert to chars.
fid = fopen(file{k});
lines = fread(fid, inf, '*char')';

% Find and replace.
text = regexprep(text, expression, replacement);

lines = regexprep(lines, expression, replacement);

% Write out the new file.
fid = fopen(file{k}, 'w');
fwrite(fid, text);
fwrite(fid, lines);

Scott Anderson

Works great. I combined it with a file search in a directory and was able to replace a word in multiple files.


Thank you, i rand your file in a loop in a folder. reduced my time drastically.
I think, it would be much better if we have a return type, confirming number of times the expression is found in the file.
just to check which files have the expression. I will try to add that code, but I dont know how to upload here

Koen Flores

Seth Bashford

Carrie Weidner

Rahul Raman

Santoshkumar Kadi

ceyhun sezenoglu

Albert Schwinn

Great stuff

Sahil Kalra

Thank you Tucker McClure,
I din find much help but I have solved my problem of converting [x1 x11 x111] by other means using the same function....

First change all occurring of x111
thereafter x11 and
last x1
This is the only technique one should follow to work with this code.

but if I do reverse this code will convert [x1 x11 x111] to [Cor(1) Cor(1)1 Cor(1)12]

Thank you so much
Code is really well written

Tucker McClure

Hi Sahil,

Please see the description above or:

help find_and_replace;

These explain how to do what you are trying to do.

Thanks Mahmudual Hasan, Sandy Jones, and Qing Xi Ooi!

Sahil Kalra

The file replace partial words
e.g. x1 has to be change to Cor(1)
it will replace x1, x11, x112 to Cor(1), Cor(1)1, Cor(1)12
hence it need to be amend

Mahmudul Hasan

Thanks a lot.

Sandy Jones

Ripper, thanks.

Qing Xi Ooi

Thank you so much. This is very helpful!

Tucker McClure

Thanks for the updated rating, Rami.

The problem was that the input wasn't a list of files, but was a search pattern. The utility expects a list of actual files (with full or relative paths).

If one wanted to replace 'cat' with 'dog' in *any* file called 'pets.m' on the path, one could do so like this:

find_and_replace(which('-all', 'pets.m'), 'cat', 'dog');

Rami AbouSleiman

Rami AbouSleiman

If you are trying to replace files under the current directory the code fails because of line 57: if ~exist(file{k}, 'file')

The exist function will return a zero and the function will not execute.


Very simple and absolute perfect code.

Adam Danz

Easy to read, straight-forward coding. Thanks.


great. Thanks!

MATLAB Release Compatibility
Created with R2013a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired: strrepfile

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!