循环文本文件,用0.00替换连续的星号

时间:2014-11-25 21:20:12

标签: matlab text replace

所有

我正在编写一个matlab程序来读取文本数据并重新排列。现在我遇到了一个新问题。

当我将数据写入csv文件时,有随机丢失的数据标记为******,如下所示导致我的程序终止。

2055   6  17  24.2 29.57  7.02******  0.99  2.65  2.73  4.09  0.11

任何人都可以帮我一个小程序来遍历文件夹中的所有文本文件,并用0.00替换连续的星号?星星总是在第33至38列,占据6个空格。我希望将它更改为两个空格,后跟0.00。

谢谢, 詹姆斯

1 个答案:

答案 0 :(得分:0)

对于给定的文本文件,您可以将其读入内存,将星号替换为所需的文本,然后覆盖原始文本文件:

filename = 'blah.txt'

% Read it into memory
fid = fopen(filename, 'r');
scanned_fields = textscan(fid, '%s', 'Delimiter','\n');
fclose(fid);
% The first (and only) field of textscan will be our cell array of text
lines = scanned_fields{1};

% Replace the asterisks with the desired text
lines = strrep(lines, '******', '  0.00');

% Overwrite the original file
fid = fopen(filename, 'w');
fprintf(fid, '%s\n', lines{:});
fclose(fid);

要对目录中的所有文本文件执行此操作,可以使用dir获取当前目录中以“.txt”结尾的文件列表:

files = dir('*.m');
filenames = {files.name};

然后遍历文件:

for ii = 1:length(filenames)
    filename = filenames{ii};

    % Read it into memory
    fid = fopen(filename, 'r');
    scanned_fields = textscan(fid, '%s', 'Delimiter','\n');
    fclose(fid);
    lines = scanned_fields{1};

    % Replace the asterisks with the desired text
    lines = strrep(lines, '******', '  0.00');

    % Overwrite the original file
    fid = fopen(filename, 'w');
    fprintf(fid, '%s\n', lines{:});
    fclose(fid);

    % Go on to the next file
end

当然,我建议在运行此目录之前创建此目录的备份副本,以防出现意外情况。

相关问题