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

1 view (last 30 days)
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 Comment
jgillis16
jgillis16 on 17 Jun 2015
I need to transport the lines in my text file that have a '~' in the 5th column to another file.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 17 Jun 2015
Edited: Guillaume on 17 Jun 2015
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.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!