How to skip some strings in a text file

조회 수: 30 (최근 30일)
Mohammad Hossein Khalili Samani
Mohammad Hossein Khalili Samani 2019년 8월 23일
Hey guys,
I want to skip the lines until I reach the two numeric data columns beneath the "lag time(s)" and "g2-1" (it would be the 18th line) and plot them as x,y respectively. So basically I want to tell it to ignore first 18 lines while reading file, and after that, in each line put the number in each column in either x or y.
Your help will be appreciated, thanks.
  댓글 수: 2
Walter Roberson
Walter Roberson 2019년 8월 23일
textscan() with 'HeaderLines', 18
dpb
dpb 2019년 8월 24일
And, if you don't know the headerlines count a prior, calling detectImportOptions will in a case such as the above file, determine it for you.

댓글을 달려면 로그인하십시오.

답변 (1개)

Allen
Allen 2019년 8월 24일
If you do not have a set number of header lines, but know the content of the last header line, you can read a portion of the file and perform a text match test to find the last header line. Rewind the scan counter and rescan the entire file using textscan(..., 'HeaderLines',LastHeaderLine). Example provided below.
% Open file and read first 100 lines as text.
filename = '150 dls.txt';
fid = fopen(filename);
C = textscan(fid,'%s',100,'delimiter','\n');
% Search scanned text for expected match of last header line and get its index value.
index = find(contains(C{1},'lag time(s)'),1);
% Rewind the scanline counter for the fid and read all lines in the file following the last header line.
frewind(fid)
expr = '%f%f'; % Expression format for 2-columns of floating point numbers
delim = ','; % Comma delimiter used in example but may need to change to meet your data
output = cell2mat(textscan(fid,expr,'headerlines',index,'delimiter',delim));
  댓글 수: 2
Walter Roberson
Walter Roberson 2019년 8월 24일
Something close to this should work
fid = fopen(filename);
fgets(fid); %discard leading date
output = cell2mat(textscan(fid, '%f%f', 'delimiter', ',', 'CommentStyle', {'Pseudo Cross Correlation', 'lag time'}) );
fclose(fid)
Mohammad Hossein Khalili Samani
Mohammad Hossein Khalili Samani 2019년 8월 25일
Thank you so much!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by