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

1 次查看(过去 30 天)
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;

采纳的回答

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