user3641311
user3641311

Reputation: 185

Find and replace text file Matlab

I'm writting a Matlab code that generates an array number and it should replace that each number in a text file (that already exists) and replace all instances with that. The number should be in string format. I've achieved this:

ita='"';
for i=1:size(z,2)
word_to_replace=input('Replace? ','s');
tik=input('Replacement? ','s');
coluna=input('Column? ');
files = dir('*.txt');
for i = 1:numel(files)
    if ~files(i).isdir % make sure it is not a directory
        contents = fileread(files(i).name);
        fh = fopen(files(i).name,'w'); 
        val=num2str(z(i,coluna));
        word_replacement=strcat(tik,val,ita);
        contents = regexprep(contents,'word_to_replace','word_replacement');
        fprintf(fh,contents); % write "replaced" string to file
        fclose(fh) % close out file
    end
end
end

I want the code to open the file#1 ('file.txt'), find and replace all instances 'word_replacement' with 'word_to_replace' and save to the same file. The number of txt files is undefined, it could be 100 or 10000.

Many thanks in advance.

Upvotes: 1

Views: 2998

Answers (1)

rayryeng
rayryeng

Reputation: 104464

The problem with your code is the following statement:

contents = regexprep(contents,'word_to_replace','word_replacement');

You are using regular expressions to find any instances of word_to_replace in your text files and changing them to word_replacement. Looking at your code, it seems that these are both variables that contain strings. I'm assuming that you want the contents of the variables instead of the actual name of the variables.

As such, simply remove the quotations around the second and third parameters of regexprep and this should work.

In other words, do this:

contents = regexprep(contents, word_to_replace, word_replacement);

Upvotes: 2

Related Questions