Use Delimiter only once in row when reading .txt files

4 views (last 30 days)
Hi all,
I have the following issue:
I want to read a .txt file which looks like this:
$CM_TIME 11:44 AM
$CM_OPERATOR Microscope Administrator
$CM_INSTRUMENT Microscope
$CM_NAME Sample 34
$CM_FRAME_SIZE 1024 1024
I want to separate this text into TWO columns, at each first space in each row. Thus, separation between TIME and 11:44, OPERATOR and JEM etc.
However, using the 'space' as a delimiter with the function textscan will also separate JEM and Administrator, while I want them to be regarderd as one string.
The part of code I'm trying it with now looks as follows:
fileID = fopen('File.txt','r');
formatSpec = '%s %s';
sizeA = [74 2];
DATA = textscan(fileID,formatSpec,sizeA,'Delimiter',' ');
Current version is Matlab2019a
Your help would be more than welcome!

Accepted Answer

Star Strider
Star Strider on 16 Nov 2020
Try this:
C = {'$CM_TIME 11:44 AM'
'$CM_OPERATOR Microscope Administrator'
'$CM_INSTRUMENT Microscope'
'$CM_NAME Sample 34'
'$CM_FRAME_SIZE 1024 1024'};
Out = regexp(C, ' ', 'split','once');
Out1 = Out{1}
Out2 = Out{2}
Out3 = Out{3}
Out4 = Out{4}
Out5 = Out{5}
producing:
Out1 =
1×2 cell array
{'$CM_TIME'} {'11:44 AM'}
Out2 =
1×2 cell array
{'$CM_OPERATOR'} {'Microscope Administrator'}
Out3 =
1×2 cell array
{'$CM_INSTRUMENT'} {'Microscope'}
Out4 =
1×2 cell array
{'$CM_NAME'} {'Sample 34'}
Out5 =
1×2 cell array
{'$CM_FRAME_SIZE'} {'1024 1024'}
.
  2 Comments
Arno van Hoof
Arno van Hoof on 16 Nov 2020
Thanks for you quick answer but, loading the .txt file will give the error:
Error using load
Number of columns on line 2 of ASCII file XXXXX
In other words, how do I then load the txt without using delimiters?
Star Strider
Star Strider on 16 Nov 2020
My pleasure!
I have no idea what the problem is, since I cannot follow your description. If you save ‘Out’, it should load correctly. Otherwise, run my code on the file you load to parse them afterwards.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!