File Exchange

image thumbnail

Find and Replace in Files

version 1.1.0.1 (3.79 KB) by

Replace the specified text in a list of files with new text.

17 Downloads

Updated

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 (14)

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

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

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.

VEERU TALREJA

Very simple and absolute perfect code.

Adam Danz

Adam Danz (view profile)

Easy to read, straight-forward coding. Thanks.

Mazi

Mazi (view profile)

great. Thanks!

Updates

1.1.0.1

Updated license

1.1

Updated trademarks.

MATLAB Release
MATLAB 8.1 (R2013a)
Acknowledgements

Inspired: strrepfile

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video