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 Center および File ExchangeData Import and Export についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by