Replacing and Inserting a text in an ASCII file

20 ビュー (過去 30 日間)
AP
AP 2011 年 6 月 5 日
コメント済み: Walter Roberson 2018 年 1 月 1 日
How can I insert a text with multiple lines and also replace a text in an ASCII file?

回答 (3 件)

Jan
Jan 2011 年 6 月 6 日
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 2011 年 6 月 5 日

Mireia Fontanet
Mireia Fontanet 2017 年 12 月 28 日
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 件のコメント
Walter Roberson
Walter Roberson 2018 年 1 月 1 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by