How do I replace a single word in a text file while maintaining all other text?

1 次查看(过去 30 天)

I have a text file (Original_Text.txt) containing the following lines;

ESPN is on sale

Other text

ESPN can be found here

some more text

ESPN costs this much

Last of the text

I am attempting to replace ESPN with ESPN_Magazine while retain all other text in the file. The resulting Modified_Text.txt file should contain the following;

ESPN_Magazine is on sale

Other text

ESPN_Magazine can be found here

some more text

ESPN_Magazine costs this much

Last of the text

I am using the following MATLAB code;

% Clear variables, close all open files, and clear out the command window
clear all;
fclose('all');
clc;
% open files for reading and writing
Original_File = fopen('Original_Text.txt','r') ;
Modified_File = fopen('Modified_Text.txt','w') ;
% Replace all occurences of ESPN with ESPN_Magazine while retain all other
% text in the file
while ( ~feof(Original_File) )
  % read line from original text file
  str = fgets(Original_File) ;
  % match line to regular expression to determine if replacement needed
  match = regexp(str,'ESPN ', 'match') ;
  % if ESPN is to be replaced
  if ( ~isempty(match) ) 
    str = ['ESPN_Magazine ', char(10)] ;
  end
  % write line to modified text filewriting file
  fwrite(Modified_File,str) ;
end
fclose('all');

And I’m getting the following result:

ESPN_Magazine

Other text

ESPN_Magazine

some more text

ESPN_Magazine

Last of the text

How do I get MATLAB to include the rest of the text from the original file?

采纳的回答

dpb
dpb 2015-8-26
编辑:dpb 2015-8-26
...
if ~isempty(match)
str = strrep(str,'ESPN','ESPN_Magazine ');
end
  2 个评论
dpb
dpb 2015-8-27
编辑:dpb 2015-8-28
And actually, you only need
while ~feof(Original_File)
str = fgets(Original_File);
fwrite(Modified_File,strrep(str,'ESPN','ESPN_Magazine ');
end
there's no need to even test for the inclusion of the string first, strrep will do that automagically. One further step is that can do without the temporary variable str as well.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by