我有一个 test.txt 文件,其中包含
bla bla bla
ble ble
BEGIN_SCAN
100 150
200 300
150 800
END_SCAN
blebleble
blublublu
我只想更改此矩阵之间BEGIN_SCAN
的数字END_SCAN
M = [100 125;
200 350;
150 835]
将结果保存在result.txt
文件中。
任何想法?
我有一个 test.txt 文件,其中包含
bla bla bla
ble ble
BEGIN_SCAN
100 150
200 300
150 800
END_SCAN
blebleble
blublublu
我只想更改此矩阵之间BEGIN_SCAN
的数字END_SCAN
M = [100 125;
200 350;
150 835]
将结果保存在result.txt
文件中。
任何想法?
您可以使用fseek移动到文件中的特定位置(当然,您首先必须找到它),然后使用fprintf覆盖该行上的内容。
例如,这在export_fig函数eps_remove_background
中用于从文件中删除一行。
这应该这样做:
txt = fileread('test.txt');
rows = regexp(txt,'\n','split');
[Lia, irows_begin] = ismember('BEGIN_SCAN', rows);
[Lia, irows_end] = ismember('END_SCAN', rows);
M_before = rows(irows_begin+1:irows_end-1);
M_before = cellfun(@(x) cell2mat(cellfun(@(y) str2num(y), strsplit(x, ' '), 'un', 0)), M_before, 'un', 0);
M_before = cell2mat(M_before(:));
M = [M_before(:,1) [125;350;835]];
M = num2cell(M, 2);
M = cellfun(@num2str, M, 'un', 0)';
rows = [rows(1:irows_begin) M rows(irows_end:end)];
fid = fopen('result.txt','wt');
fprintf(fid, '%s\n', rows{:});
fclose(fid);
改编自@Will 的正常工作的答案:
fid=fopen('test.txt');
txt =textscan(fid,'%s','delimiter','\n');
rows = txt{1,1};
irows_begin = find(ismember(rows,'BEGIN_SCAN'));
irows_end = find(ismember(rows,'END_SCAN'));
fclose(fid)
M_before = rows(irows_begin+1:irows_end-1);
M_before=cellfun(@str2num,M_before,'UniformOutput',false);
M_before = cell2mat(M_before(:));
M = [M_before(:,1) [125;350;835]];
M = num2cell(M, 2);
M = cellfun(@num2str, M, 'un', 0);
rows = [rows(1:irows_begin); M; rows(irows_end:end)];
fid = fopen('result.txt','wt');
fprintf(fid, '%s\n', rows{:});
fclose(fid);