Import and modify " .txt" files

1 visualización (últimos 30 días)
johnmay
johnmay el 26 de Nov. de 2015
Editada: Walter Roberson el 31 de Jul. de 2022
Hi
I have some ".txt" files with this structure :
useless
useless
useless
...
data
data
...
useless
useless
useless
data
...
And I would like to have a .txt file like this :
data
data
data
...
I just know that each first line of data section begins with '1' but the length of the headerline (useless) is not fixed ! So I would like to iterate until lines begins with '1' and then keep the data.
How would you do that the easiest way ?
Thanks a lot
  5 comentarios
johnmay
johnmay el 26 de Nov. de 2015
Here is a sample file. As you can see 'X-Axis Size' gives me the number of measurement points (10) and I still have this value with some code (strfind...)
johnmay
johnmay el 26 de Nov. de 2015
Sorry, here it is... And file2 is what I want
Many thanks

Iniciar sesión para comentar.

Respuestas (2)

Thorsten
Thorsten el 26 de Nov. de 2015
Copy those lines that have four numbers:
fid = fopen('file.txt', 'r');
fid2 = fopen('file2.txt', 'w');
line = fgets(fid);
while line ~= -1
[~, count] = sscanf(line, '%f');
if count == 4
fprintf(fid2, '%s', line);
end
line = fgets(fid);
end
fclose(fid)
fclose(fid2)
  6 comentarios
Thorsten
Thorsten el 26 de Nov. de 2015
You mean reading and write to the same file? No, I don't think so.
johnmay
johnmay el 26 de Nov. de 2015
Last question : when using 'fprintf' is there a way to write only the 'x' first columns of my line? and not the whole line So that the final file has a constant number of columns and could be opened easily ?
Many thanks

Iniciar sesión para comentar.


johnmay
johnmay el 26 de Nov. de 2015
Last question : when using 'fprintf' is there a way to write only the 'n' first columns of my line? and not the whole line. So that the final file has a constant number of columns (n) and could be opened easily ?
Many thanks
  2 comentarios
Walter Roberson
Walter Roberson el 27 de Nov. de 2015
Before the loop:
n = 2; %whatever is appropriate
fmt = repmat('%f ', 1, n);
fmt(end:end+1) = '\n'; %newline, unrelated to the variable 'n'
In the loop:
[data, count] = sscanf(line, '%f');
if count >= n
fprintf(fid2, fmt, data(1:n));
end
johnmay
johnmay el 1 de Dic. de 2015
Thanks a lot. I just tried but it doesn't work, it seems like it concatenates data in a single line.. Anyway many thanks

Iniciar sesión para comentar.

Categorías

Más información sobre Model Import 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