How do I replace a single word in a text file while maintaining all other text?
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
More Answers (0)
Categories
Find more on Characters and Strings in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!