Matlab 查找和替换文本文件

Matlab 查找和替换文本文件,matlab,file,replace,find,Matlab,File,Replace,Find,我正在编写一个Matlab代码,生成一个数组编号,它应该替换文本文件(已经存在)中的每个编号,并用该编号替换所有实例。数字应为字符串格式。我做到了这一点: 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)

我正在编写一个Matlab代码,生成一个数组编号,它应该替换文本文件(已经存在)中的每个编号,并用该编号替换所有实例。数字应为字符串格式。我做到了这一点:

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
我想让代码打开文件#1('file.txt'),找到所有实例“word_replacement”并替换为“word_to_replace”,然后保存到同一个文件中。txt文件的数量未定义,可能是100或10000


非常感谢。

您的代码存在以下问题:

contents = regexprep(contents,'word_to_replace','word_replacement');
您正在使用正则表达式在文本文件中查找
word\u to\u replace
的任何实例,并将其更改为
word\u replacement
。查看您的代码,似乎这两个变量都包含字符串。我假设您想要变量的内容,而不是变量的实际名称

因此,只需删除
regexprep
的第二个和第三个参数周围的引号,就可以了

换句话说,请执行以下操作:

contents = regexprep(contents, word_to_replace, word_replacement);