Replacing and Inserting a text in an ASCII file

4 vues (au cours des 30 derniers jours)
AP
AP le 5 Juin 2011
How can I insert a text with multiple lines and also replace a text in an ASCII file?

Réponses (3)

Jan
Jan le 6 Juin 2011
You can read the file into a string or cell string, perform the operations and write it back again:
Replace in string method:
Str = fileread(FileName);
Str2 = strrep(Str, 'toReplace', 'Replacement');
FID = fopen(FileName, 'w');
if FID < 0, error('Cannot open file'); end
fwrite(FID, Str2, 'uchar');
fclose(FID);
To insert lines in addition:
CStr = regexp(fileread(FileName), char(10), 'split');
CStr2 = strrep(CStr, 'toReplace', 'Replacement');
CStr2 = cat(2, CStr2(1:10), {'Inserted line'}, CStr2(11:end));
FID = fopen(FileName, 'w');
if FID < 0, error('Cannot open file'); end
fprintf(FID, '%s\n', CStr2{:});
fclose(FID);
Care for modern CHAR(10) or DOS style CHAR([13, 10]) linebreaks on demand.

Walter Roberson
Walter Roberson le 5 Juin 2011

Mireia Fontanet
Mireia Fontanet le 28 Déc 2017
Dear, I have two file, the first one is variables.txt and the seconf one is called selector.txt. I want to replace the first line of variables.txt to the 20th line of selector.txt. Then I want to repeat the same but replacinf the second line of variables.txt with the same line of selector.txt. How can I do it?
  1 commentaire
Walter Roberson
Walter Roberson le 1 Jan 2018
variables_lines = regexp( fileread('variables.txt'), '\r?\n', 'split');
selector_lines = regexp( fileread('selector.txt'), '\r?\n', 'split');
selector20 = selector_lines{20};
NL = sprintf('\n');
num_variables = length(variables_lines);
outputs = cell(num_variables,1);
for K = 1 : num_variables
temp = variables_lines;
temp{K} = selector20;
outputs{K} = strjoin(temp, NL);
end
Now outputs is a cell array of character vectors, each one being copied from variables.txt but with one line of it replaced with the content of line 20 of selector.txt .
This is probably not the output form you were thinking of, but you said nothing about how you wanted to use the results of the substitution.

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by