File Exchange

image thumbnail

Find and Replace in Files

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

6 Downloads

Updated 01 Sep 2016

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.

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)
end

% 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.']);
end

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

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;
end
tline = fgetl(fid);ln = ln+1;
end
if ~isempty(lines)
n_tgtf = n_tgtf+1;
matches{n_tgtf,1} = file{k};
matches{n_tgtf,2} = lines;
end
fclose(fid);
else
% Read in the file as binary and convert to chars.
fid = fopen(file{k});
lines = fread(fid, inf, '*char')';
fclose(fid);

% 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);
fclose(fid);
end
end

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

subhash

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

Rahul Raman

Great stuff

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

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

Thanks a lot.

Sandy Jones

Ripper, thanks.

Qing Xi Ooi

Thank you so much. This is very helpful!

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');

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.

Mazi

great. Thanks!

Updates

1.1.0.1

Updated license

1.1.0.0

Updated trademarks.

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

Inspired: strrepfile

Discover Live Editor

Create scripts with code, output, and formatted text in a single executable document.


Learn About Live Editor