Effacer les filtres
Effacer les filtres

How can MATLAB find and replace a word in a text that contains multiple lines?

4 vues (au cours des 30 derniers jours)
E.g. if there is a text file with 57 lines and I want a small change of a word in line 54.
  2 commentaires
dpb
dpb le 23 Déc 2017
If you do mean in a text file, then "Houston, we (may) have a problem!" as text files are sequential and any change in the chosen word that changes its length will change the length of the file. Also, writing to a file has the effect of truncating the file from that point forward.
The only (practical) way to do this is to read the file into memory and make the change there and then rewrite the whole file.
GEORGIOS BEKAS
GEORGIOS BEKAS le 23 Déc 2017
can I cleverly point out these points beforehand by using a special character like ',,' and let MATLAB do the job at each iteration?

Connectez-vous pour commenter.

Réponse acceptée

Image Analyst
Image Analyst le 23 Déc 2017
You forgot to attach the file. So use fgetl() until you read line 57, then use strrep() on that line.
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = 'C:\Program Files\MATLAB';
if ~exist(startingFolder, 'dir')
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
% Open the file.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
numLinesRead = 1;
while ischar(textLine)
% Read the remaining lines of the file.
fprintf('%s\n', textLine);
% Read the next line.
textLine = fgetl(fileID);
numLinesRead = numLinesRead + 1;
if numLinesRead == 57
% Use strrep() on textLine
changedLine = strrep(textLine, oldText, newText);
% Then do something with changedLine.
end
end
% All done reading all lines, so close the file.
fclose(fileID);

Plus de réponses (0)

Catégories

En savoir plus sur Data Import and Export dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by