Transfer certain rows of a text file into a new text file
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
jgillis16
am 17 Jun. 2015
Kommentiert: jgillis16
am 17 Jun. 2015
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;
Akzeptierte Antwort
Guillaume
am 17 Jun. 2015
Bearbeitet: Guillaume
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Import and Export finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!