首页 > 解决方案 > 如何分离日志文件?

问题描述

我有一个这样的日志文件:

00:00.262   ID:1    info
00:00.268   ID:4    info
00:00.268   ID:6    info
00:00.268   ID:24   info
00:00.268   ID:17   info
00:00.268   ID:20   info
00:00.268   ID:13   info
00:00.268   ID:18   info
00:00.268   ID:14   info
00:00.268   ID:23   info
00:00.268   ID:19   info
(...)

所以,我开发了这个算法来根据 ID 将日志文件分隔在单独的文件中。

% Read file
Data = textscan(log_fileID, '%s', 'delimiter', '\n', 'whitespace', '');
CStr = Data{1};

% Create separate files 
for i = 1:1:number

    IndexC = strfind(CStr, sprintf('ID:%d', i));
    Index = find(~cellfun('isempty', IndexC)); %
    % Delete lines
    if ~isempty(Index)
     Aux = CStr(Index);
    end

    % Save the file
    savePath = './Node/'; % Save files directory
    FID = fopen([savePath sprintf('Node %d.0.txt', i)],'w'); 
    if FID == -1, error('Cannot open file'), end
    fprintf(FID, '%s\n', Aux{:});

    fclose(FID);   
end

但是,我有一个问题。

当我创建一个 ID:1 的文件时,所有出现 ID:1、ID:10、ID:11、ID:12、...、ID:19 的行都保存在文件中。

我怎样才能用简单的方法解决这个问题?谢谢

标签: matlab

解决方案


我使用 matlab 的内置导入工具生成一个函数,用于将数据导入表中。这使得它更容易操纵。假设您已将日志文件加载到名为的变量中,test您可以使用最少的代码将其写入info以 id 命名的文件。我还没有针对多个 id 具有相同名称的实例检查代码,因此您可能需要检查一下。您最终应该得到名为“ID1.txt”、“ID2.txt”等的文本文件。

 function test = importfile(filename, dataLines)
%IMPORTFILE1 Import data from a text file
%  TEST = IMPORTFILE1(FILENAME) reads data from text file FILENAME for
%  the default selection.  Returns the data as a table.
%
%  TEST = IMPORTFILE1(FILE, DATALINES) reads data for the specified row
%  interval(s) of text file FILENAME. Specify DATALINES as a positive
%  scalar integer or a N-by-2 array of positive scalar integers for
%  dis-contiguous row intervals.
%
%  Example:
%  test = importfile1("path/to/file.txt", [1, Inf]);
%
%  See also READTABLE.
%
% Auto-generated by MATLAB on 25-Jul-2019 07:19:02

%% Input handling

% If dataLines is not specified, define defaults
if nargin < 2
    dataLines = [1, Inf];
end

%% Setup the Import Options
opts = delimitedTextImportOptions("NumVariables", 4);

% Specify range and delimiter
%opts.DataLines = [1, Inf];
opts.DataLines = dataLines;
opts.Delimiter = ["ID:","   "];

% Specify column names and types
opts.VariableNames = ["Time","IDNum",  "Info","Var4"];
opts.SelectedVariableNames = ["Time", "IDNum", "Info"];
opts.VariableTypes = ["char", "double", "char", "char"];
opts = setvaropts(opts, [1, 3, 4], "WhitespaceRule", "trim");
opts = setvaropts(opts, [1, 2, 3], "EmptyFieldRule", "auto");
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
opts.ConsecutiveDelimitersRule = "join";

% Import the data
test = readtable(filename, opts);

end

unq = unique(test.IDNum);
savePath = './Node/';
for i = 1:size(unq,1)
    fullPath = [savePath,'ID',char(num2str(test.IDNum(i))),'.txt'];
    %generate index for info
    idx = test.IDNum == unq(i);
    info = test.Info(idx);
    FID = fopen(fullPath,'w');
    fprintf(FID,'%s',info);
    fclose(FID);
end

推荐阅读