Reading .txt with multiple delimiters

52 views (last 30 days)
Another Mouse
Another Mouse on 11 Aug 2021
Answered: Jeremy Hughes on 14 Aug 2021
I want to read a .txt file with multiple delimiters. One line of the file looks like this:
Sensor 1| 00150| 2283 mSec| 0.221 3.183 11.055| 0.0353 0.0023 -0.6950 0.7182|
I had originally hardcoded to read the file like this, but occasionally it will incorrectly read NaN (probably due to unseen differences in spacing on some lines of the data file) when there is clearly a value present. This works for some files but not all.
fileID = fopen('R1.txt','r');
formatSpec = '%40c %8f %9f %6f %1c %11f %10f %8f %8f';
A=textscan(fileID,formatSpec);
I then tried using a community board suggestion ( https://www.mathworks.com/matlabcentral/answers/231118-how-to-read-a-text-file-with-delimiter ) to read it using the following code, but could not figure out how to separate the groups of numbers within colunms 4 and 5 of fieldarray:
%read file
filestr = fileread('R1.txt');
%break it into lines
filebyline = regexp(filestr, '\n', 'split');
%split by fields
filebyfield = regexp(filebyline, '\|', 'split');
%pad out so each line has the same number of fields
numfields = cellfun(@length, filebyfield);
maxfields = max(numfields);
fieldpattern = repmat({[]}, 1, maxfields);
firstN = @(S,N) S(1:N);
filebyfield = cellfun(@(S) firstN([S,fieldpattern], maxfields), filebyfield, 'Uniform', 0);
%switch from cell vector of cell vectors into a 2D cell
fieldarray = vertcat(filebyfield{:});
Is there a better way to approach this?

Answers (2)

Wan Ji
Wan Ji on 14 Aug 2021
If each line in the file is of the same format, I recommend the following formatSpec
formatSpec = 'Sensor %d| %d| %f mSec| %f %f %f| %f %f %f %f|';

Jeremy Hughes
Jeremy Hughes on 14 Aug 2021
Readtable accepts multiple delimiters. Try this:
T = readtable(filename,"Delimiter",[" ","|"])

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!