Matlab 如何替换字符串(读取文件后)并将更新的内容存储在新文件中?
我不熟悉MATLAB脚本编写,我试图将文件(数据文件)的内容读入数组,Matlab 如何替换字符串(读取文件后)并将更新的内容存储在新文件中?,matlab,Matlab,我不熟悉MATLAB脚本编写,我试图将文件(数据文件)的内容读入数组,C,比较数组中的特定字符串(“hello”),如果找到该字符串,则将其替换为另一个字符串(“ciao”),并相应地更新该文件,并将其存储在新文件(newfile.txt)中。我有以下代码,请帮我找出错误: C = textread(data_files, '%s', 'delimiter', '\n'); file_content = fileread(data_files); expr ='\hello'; fileread
C
,比较数组中的特定字符串(“hello”),如果找到该字符串,则将其替换为另一个字符串(“ciao”),并相应地更新该文件,并将其存储在新文件(newfile.txt)中。我有以下代码,请帮我找出错误:
C = textread(data_files, '%s', 'delimiter', '\n');
file_content = fileread(data_files);
expr ='\hello';
fileread_info = regexp(filetext, expr, 'match');
length_fileread_info=length(fileread_info);
if length_fileread_info >=1
C = C(cellfun(@isempty, strrep(filetext,'hello','Ciao') ));
end
fid = fopen('newfile.txt', 'wt');
fprintf(fid, '%s\n', C{:});
fclose(fid);
end
我认为我没有正确地实现cellfun
。我得到以下错误
??? Error using ==> cellfun
Input #2 expected to be a cell array, was char instead.
请给我忠告 您可以使用
regexprep
:
>> newC = regexprep( file_content, 'hello', 'Ciao' );
>> fid = fopen('newfile.txt', 'wt');
>> fprintf(fid, '%s', newC);
>> fclose(fid);
您遇到了什么错误?这里的代码
strrep(filetext,'hello','Ciao')
正在返回一个字符,它应该是一个单元格。在使用之前检查代码的输出。你为什么要首先使用cellfun?另一方面,文件是否太大,无法一次读取和存储,还是相对较小(几MB)?