How to Differentiate between '\n' and CR/LF when reading in text files in MATLAB

조회 수: 26 (최근 30일)
I am trying to read in a text file where each row contains a string. Some rows contain the character combination '\n' and '\r', and then all rows end with a CR and LF marker (I opened the file in Notepad++ to see this). For example:
First Name
Birthdate
Average\nLength
Avoid\rWater
...and so on.
The issue is that when I use textscan and set either '\n' or '\r' as the delimiter, MATLAB parses the incoming file at every '\n' or '\r' and CR or LF, where I need to only have actual carriage returns and line feeds break the line. Is there some sort of identifier I can use to differentiate a CR/LF from '\n' and '\r'?
fid=fopen('text.txt', 'r+');
full=textscan(fid, '%s', 'Delimiter', '\n') % I tried with '\r' as delimiter as well, and the result is the same
printFile=fopen('results.txt', 'at');
for i=1:length(full{1})
str=full{1}{i};
str=strrep(str, '\n', '$'); % I need to input a '$' as a manual delimiter in place of actual CR and LF.
% However this will replace both '\n' *and* CR/LF with '$'.
fprintf(printFile, '%s$', str);
end
fclose all;

채택된 답변

akazakov
akazakov 2016년 7월 20일
I've been sitting with this problem for a while, and the second I posted a question I figured it out :)
a=sprintf('\n') % a now equals a line feed
b=sprintf('\r') % b now equals a carriage return
Using these as delimiters directly solves my problem. So given my original sample code:
fid=fopen('text.txt', 'r+');
full=textscan(fid, '%s', 'Delimiter', sprintf('\r'));
fclose all;
% This reads in the text file, creating a new line at every carriage return
% and doing nothing when it sees a '\n' or '\r'

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by