How to use sscanf to read data file with two delimiter

23 views (last 30 days)
Hi, I am trying to read the following text (.txt) file using sscanf
YYYY-MM-DD HH:MM MOD UNMO PRESS TEM RH BATT
UTC /hr /hr mb C % V
2011-01-21 00:02 1608 1008 1001.2 12 98 11.7
2011-01-21 01:02 1602 1010 999.4 8 100 11.7
.
.
This is part of the script I am trying to run
fid1 = fopen('counts.txt');
% Skip first two rows
line = fgets(fid1);
line = fgets(fid1);
while ~feof(fid1)
line = fgets(fid1); %# read line by line
A = sscanf(line,'%i4,%i2,%i2,%i2,%i2,%i4,%i4,%f6.1,%i3,%i3 %f4.1')
.
.
It is only giving me 2011. I would like to know how to deal with the two delimiters (dash and colon) in each line.
Thank you
  1 Comment
David
David on 21 Jan 2022
The sscanf documentation says:
Literal Text to Ignore
sscanf ignores specified text immediately before or after the conversion specifier.
Example: Level%u reads 'Level1' as 1.
Example: %uStep reads '2Step' as 2.
So maybe:
line = "2011-01-21 00:02 1608 1008 1001.2 12 98 11.7"
A = sscanf(line,'%i-%i-%i %i:%i %i %i %f %i %i %f');

Sign in to comment.

Answers (1)

Oleg Komarov
Oleg Komarov on 15 Feb 2011
I suggest the following approach:
fid = fopen('C:\Users\Oleg\Desktop\trial.txt');
data = textscan(fid,'%s%s%f%f%f%f%f%f','HeaderLines',2,'MultipleDelimsAsOne',true);
fid = fclose(fid);
% Convert dates
[y,m,d,HH,MM] = datevec(strcat(char(data{1}),'-',char(data{2})),'yyyy-mm-dd-HH:MM');
data = [y m d HH MM data{:,3:end}]
data =
2011 1 21 0 2 1608 1008 1001.2 12 98 11.7
2011 1 21 1 2 1602 1010 999.4 8 100 11.7
Oleg

Community Treasure Hunt

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

Start Hunting!