我有一个这样的日志文件:
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的行都保存在文件中。
如何用简单的方法解决此问题? 谢谢
答案 0 :(得分:0)
我使用了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