フィルターのクリア

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

2 ビュー (過去 30 日間)
Brad
Brad 2015 年 8 月 26 日
編集済み: dpb 2015 年 8 月 28 日

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 件のコメント
Brad
Brad 2015 年 8 月 27 日
Whoops. I forgot all about the function strrrep.
Thanks dqb.
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 Center および File ExchangeEnvironment and Settings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by