View License

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

» Watch video

Highlights from
Find and Replace in Files

4.6 | 9 ratings Rate this file 34 Downloads (last 30 days) File Size: 3.79 KB File ID: #42877 Version:

Find and Replace in Files


Tucker McClure (view profile)


14 Aug 2013 (Updated )

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

| Watch this File

File Information

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.


This file inspired Strrepfile.

Required Products MATLAB
MATLAB release MATLAB 8.1 (R2013a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (11)
19 Feb 2017 Tucker McClure

Tucker McClure (view profile)

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!

Comment only
18 Feb 2017 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

08 Dec 2016 Mahmudul Hasan

Thanks a lot.

02 Dec 2016 Sandy Jones

Ripper, thanks.

23 Oct 2016 Qing Xi Ooi

Thank you so much. This is very helpful!

20 Sep 2016 Tucker McClure

Tucker McClure (view profile)

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

Comment only
20 Sep 2016 Rami AbouSleiman

19 Sep 2016 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.

30 May 2015 Adam Danz

Adam Danz (view profile)

Easy to read, straight-forward coding. Thanks.

17 Dec 2014 Mazi

Mazi (view profile)

great. Thanks!

14 Aug 2013 1.1

Updated trademarks.

01 Sep 2016

Updated license

Contact us