Transfer certain rows of a text file into a new text file

조회 수: 1 (최근 30일)
jgillis16
jgillis16 2015년 6월 17일
댓글: jgillis16 2015년 6월 17일
I need to transport some lines in my text file, attached as SAMPLEFILE.txt, onto a new text file. The lines I want to transport are the lines that are marked by having a '~' in the 5th column.
For example: 18|PGC000018|0.00360|46.96508|~|14.25|0.869|0.280|0.791|~|0.91|0.107|~|-20.25|77.306|11.596|0.31|0.32|
has a '~' in the 5th column [NAMED AS GalList.morph IN THE CODE BELOW].
My current code is:
load SAMPLEFILE.txt %loads text into workspace
readCatalog( SAMPLEFILE )
fid = fopen( 'SAMPLEFILE.txt');
trashLine = fgets(fid); %Skips the first line
data = textscan(fid, '%f%s%f%f%s%f%f%f%f%f%f%f%f%f%f%f%f%f', 'Delimiter', '|', 'TreatAsEmpty','~');
fclose(fid);
GalList.pgc = data{1};
GalList.name = data{2};
GalList.ra = data{3};
GalList.dec = data{4};
GalList.morph = data{5};
GalList.app_mag = data{6};
GalList.major = data{7};
GalList.abs_mag = data{14};
GalList.dist = data{15};
GalList.err_Dist = data{16};
GalList.err_App_Mag = data{17};
GalList.err_Abs_Mag = data{18};
theta = GalList.ra * pi/12;
phi = GalList.dec * pi/180;
GalaxyList = GalList;
Q1 = GalList.morph;
  댓글 수: 1
jgillis16
jgillis16 2015년 6월 17일
I need to transport the lines in my text file that have a '~' in the 5th column to another file.

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

채택된 답변

Guillaume
Guillaume 2015년 6월 17일
편집: Guillaume 2015년 6월 17일
This will probably do what you want:
content = fileread('samplefile.txt');
linestocopy = regexp(content, '^([^|]*\|){4}~\|.*$', 'match', 'dotexceptnewline', 'lineanchors');
newfile = fopen('copiedlines.txt', 'wt');
fprintf(newfile, strjoin(linestocopy, '\n'));
fclose(newfile);
It uses a regular expression to find all the lines that start by (any number of characters but | followed by | ) repeated four times, followed by ~|, then anything up to the end of the line.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by