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

1 visualización (últimos 30 días)
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.

Respuestas (2)

Guillaume
Guillaume el 4 de Feb. de 2016
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 el 4 de Feb. de 2016
% try this
>> prefix = regexprep(filename,'\.','\t')
prefix = p01 male cond 1 loud txt
  2 comentarios
Walter Roberson
Walter Roberson el 4 de Feb. de 2016
Easier:
filename(filename == '.') = sprintf('\t');
This works because tab is just a single character, char(9)
Guillaume
Guillaume el 4 de Feb. de 2016
Editada: Guillaume el 4 de Feb. de 2016
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

Iniciar sesión para comentar.

Categorías

Más información sobre Word games en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by