File Exchange

image thumbnail

Replace strings in text file

version (1.92 KB) by Pekka Kumpulainen
REPLACEINFILE replaces characters in ASCII file using PERL


Updated 08 Jan 2009

View License

Easy and efficient way to replace strings in ASCII files.
For example replace commas ',' to points '.' in large data files for easier load.

Cite As

Pekka Kumpulainen (2020). Replace strings in text file (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (35)

Philipp Bischof

Thank you!


Paul Macey


I had trouble replacing some trouble when the string I wanted to replace had '.' symbol. I am using MATLAB 2013b on Ubuntu 12.04 kernel 3.2.0-58-generic.

I ran the function like this:
>> replaceinfile('.iq','.buf','file1.txt','file2.txt')

This function worked correctly for one line of my file (the one I wanted to change):

sOpt.suffix = '.iq';


sOpt.suffix = '.buf';

The problem occurred for this line (which I did not want to change):

sOpt.datadir = 'iqdata/';


sOpt.datadir = .bufdata/';

I found I had no problems if I ran the function either of the following ways:
>> replaceinfile('\.iq','\.buf','iqpro_setup.txt','test.txt')
>> replaceinfile('\.iq','.buf','iqpro_setup.txt','test.txt')

Maybe this is a trait of PERL, not sure. Thought I'd share on the off chance that anyone else runs into that problem.

Thanks for the code.


Works very well, I am using it to generate a batch of files from a single template. I am replacing two strings in a template and creating a file everytime. Is there a way to replace multiple strings in one shot?
The way I do it now is:
1. Open template, replace first string, save with new name.
2. Open new file, replace second string.


Great. This was just what I needed. I added a multiselect uidetfile beforehand so I could do a batch replace on a large number of files and it worked perfectly.
[files] = uigetfile('*.txt','multiselect','on');

cnt = length(files);

for i = 1:cnt
s = replaceinfile(oldStr,newStr,files{i});

Kevin J. Delaney

Fantastic! Just what I was looking for & it works great.


Congrat! good script.
Only i have one question. how to use this script with multiples files? For example i have a several files in format txt in one directory, like: 31.txt, 32.txt, 33.txt... etc
there is a way to use this script for change in all the files the commas ',' to points '.'?
Thanks in advance for your help!

Simon Funder

Very neat script - exactly what I was looking for. One request for a modification though:

Is it possible to specify exact lines in the input file that the script shall apply to, so e.g. find and replace is only done in the first 10 lines of my input file?



When I want to replace the string "AB.12345" with "AB.54321", the function also replaces "AB-12345", which are also in the original ASCII file with "AB.54321". This was not my intention. Can the author fix this?



Good job! Works great for me!

ubuntu21 T

Ehsan suggested on 02 Jan 2011 to write the code for a sort of automatical switch between different OS. In my case, I have on my computer Windows and Ubuntu 10.04 Linux, so I have replaced the line

perlCmd = sprintf('"%s"',fullfile(matlabroot, 'sys\perl\win32\bin\perl'));


if findstr('glnx',lower(computer))
perlCmd = sprintf('"%s"',fullfile('/usr/bin/perl'));
else %assume it's windows otherwise
perlCmd = sprintf('"%s"',fullfile(matlabroot, 'sys\perl\win32\bin\perl'));

I have only tested on Ubuntu 10.04 Linux, with positive results on a 240 MB file. It works like a charm and very fast.



Hello everybody!

Could somebody give me some help with this file? Perhaps and example or something like that. I am running the function with the text I want to replace but is says that there are no matches for my search. Also, does the format has to be a .bak file or could it be a .txt?

Thanks in advance for your help!

Adi Navve

Works great.
Just one suggestion, in case of calling the function with filenames without a full path the call fails if these files are not in the system path. How about adding support to this case by identifying it and building the path using "which" function?
Thanks for the submission.

Lennart van Luijk

Works exactly like it's supposed to!


would be nice if there was a matlab/linux switch automatically change between

(matlabroot, 'sys\perl\win32\bin\perl')

Johannes Schaffner

Doug Hull

Richard Holcombe

This doesn't seem to work at all for me. after running the program, the directory that contained the file now has its permissions set so that I cannot access the file, or even delete the directory containing the file. I don't know what happened to the text of the file because I can't access the file.


AH! It was siple, / is a special character, it should be expressed with a \ in front as per the comment above!

...for the next user


A host of alternative errors seem to plague me method of calling the function depending on varying my reference to a space as ' ', char(32) or 'char(32)':

??? Error using ==> replaceinfile at 64
Illegal division by zero at -e line 1, <> line 1.

??? Error using ==> replaceinfile at 64
Bareword found where operator expected at -e line
1, near "s///char"
syntax error at -e line 1, near "s///char"
Execution of -e aborted due to compilation errors.



This may be an obvious error as I am just getting into Matlab,

when I call tthe function:
[s, msg] = replaceinfile('/', ' ', 'data.dat');

i get the error:
??? Error using ==> replaceinfile at 64
Can't do inplace edit on data.dat: File exists.

Any ideas?

I have to do several substitutions in sequence in order to be able process the data appropriately, i imagine doing this by:

[s, msg] = replaceinfile( '/' , ' ' , 'data.dat');
[s, msg] = replaceinfile( ',' , '. ' , 'data.dat');

should this work?


Seems to work great overall. Couldn't get it to replace the string '//' in my ascii file, though. Get this error:

Bareword found where operator expected at -e line 1, near "%/g"
(Missing operator before g?)
syntax error at -e line 1, next token ???
Execution of -e aborted due to compilation errors.

boutonnet arnaud

'+' is a reserved symbol for regular expressions. One needs to put a '\'in front of it and then it works !

boutonnet arnaud

... If the string contains the 'plus' symbol

boutonnet arnaud

Very useful. One problem though: the function doesn't work if the string contains the symbol '+'

Oleg Komarov

Works fine...don't know what happened :)

Oleg Komarov

I have some problems with whitespaces, i want to replace tehm with a char, "X". but it places an "X" between every char.
20039 IAN43
replaceinfile(' ','X', myfile) --> 2X0X0X3X9X X XIXAXNX4X3
instead of 20039XXIAN43

John Peterson

Very nice. Could I find a Unicode version of this?

Dennis M

very nice

Butch Walker

Would be nice to have an option to replace 'first occurance' instead of automatically replacing all when the file has multiple matches and you dont want to replace them all. Otherwise, great script!

Andy G

Pretty Slick!

q w


'-nobak' option to remove backup file, fixed help a little

Now supports paths with spaces, forced overwrite of existing output file, corrected replaceing of '.' and '\'

Note on platforms

Fixed error if MATLAB path has whitespaces

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