How do I use chunks from strsplit in Matlab to save along with my data in a text file?

1 次查看(过去 30 天)
I have a list of over 600 files that I would like to extract the information from the file name and put it into the text file along with the information in the file itself.
Example:
name of file:
p01.male.cond.1.loud.txt
info in file:
0.015 120 50
0.12 121 52
0.23 119 53
0.4 122 59
I would like the file to look like this:
p01 male cond 1 loud 0.015 120 50
p01 male cond 1 loud 0.12 121 52
p01 male cond 1 loud 0.23 119 53
p01 male cond 1 loud 0.4 122 59
I used strsplit to extract the names from the file name but I do not know how to use the chunks from strsplit to put into a data file. PLEASE HELP!!! the code needs to be general enough to apply to the 600 files that I have that all have a similar name structure but different names and different file contents.

回答(2 个)

Guillaume
Guillaume 2016-2-4
You would basically loop over your files, read the content, add the prefix (see tudor's answer and related comments) to each line, and rewrite (preferably to a different file to eliminate the risk of losing data). Something like:
%filenames: a cell array of file names (strings). Possibly obtained with dir
%folder: the full path of the folder containing the files (string).
for fileindex = 1:numel(filenames)
testconditions = strsplit(filename{fileindex}, '.');
prefix = strjoin(testconditions(1:end-1), '\t');
fin = fopen(fullfile(folder, filename{fileindex}), 'rt');
fout = fopen(fullfile(folder, ['modified -', filename{fileindex}]), 'wt');
tline = fgetl(fid);
while ischar(tline)
if ~isempty(tline)
fprintf(fout, '%s\t', prefix);
end
fprintf(fout, '%s\n', tline);
end
fclose(fin);
fclose(fout);
end

tudor dima
tudor dima 2016-2-4
% try this
>> prefix = regexprep(filename,'\.','\t')
prefix = p01 male cond 1 loud txt
  2 个评论
Guillaume
Guillaume 2016-2-4
编辑:Guillaume 2016-2-4
Except that both these solution keep the original extension that is not wanted.
testconditions = strsplit(filename, '.');
prefix = strjoin(testconditions(1:end-1), '\t')
would make more sense

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Word games 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by