Azzera filtri
Azzera filtri

Replacing and Inserting a text in an ASCII file

6 visualizzazioni (ultimi 30 giorni)
AP
AP il 5 Giu 2011
How can I insert a text with multiple lines and also replace a text in an ASCII file?

Risposte (3)

Jan
Jan il 6 Giu 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 il 5 Giu 2011

Mireia Fontanet
Mireia Fontanet il 28 Dic 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 Commento
Walter Roberson
Walter Roberson il 1 Gen 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.

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by