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

1 visualización (últimos 30 días)

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?

Respuesta aceptada

dpb
dpb el 26 de Ag. de 2015
Editada: dpb el 26 de Ag. de 2015
...
if ~isempty(match)
str = strrep(str,'ESPN','ESPN_Magazine ');
end
  2 comentarios
Brad
Brad el 27 de Ag. de 2015
Whoops. I forgot all about the function strrrep.
Thanks dqb.
dpb
dpb el 27 de Ag. de 2015
Editada: dpb el 28 de Ag. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by