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

1 view (last 30 days)

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?

Accepted Answer

dpb
dpb on 26 Aug 2015
Edited: dpb on 26 Aug 2015
...
if ~isempty(match)
str = strrep(str,'ESPN','ESPN_Magazine ');
end
  2 Comments
dpb
dpb on 27 Aug 2015
Edited: dpb on 28 Aug 2015
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.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!