How to remove some lines of a file?

40 ビュー (過去 30 日間)
Bruno Souza
Bruno Souza 2018 年 2 月 19 日
コメント済み: Akira Agata 2018 年 2 月 20 日
I have a File of 8.760 lines. I'll use just the first 744 lines. How can I delete the others?
  2 件のコメント
Bob Thompson
Bob Thompson 2018 年 2 月 19 日
What type of file is it? What type of data does it contain?
The general method I would suggest would be to read the file into matlab somehow, and then remove the data you don't need before reprinting the truncated file.
Bruno Souza
Bruno Souza 2018 年 2 月 20 日
It is a .txt file. With some numbers Like this:
18.400
19.000
19.000
19.000
18.700

サインインしてコメントする。

採用された回答

Akira Agata
Akira Agata 2018 年 2 月 20 日
Assuming your file is a text file, you can extract the first 744 lines ans save it like this:
% Full path of the sample text file
filePath = fullfile(matlabroot,'examples','matlab','sonnets.txt');
% Read the file
fid = fopen(filePath,'r');
str = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
% Extract first 744 lines
str2 = str{1}(1:744);
% Save as a text file
fid2 = fopen('test.txt','w');
fprintf(fid2,'%s\n', str2{:});
fclose(fid2);
  2 件のコメント
Bruno Souza
Bruno Souza 2018 年 2 月 20 日
It is working. Can I still have the data like this?
18.400
19.000
19.000
19.000
18.700
Because the new data is like that:
18.400 19.000 19.000 19.000 18.700
Akira Agata
Akira Agata 2018 年 2 月 20 日
> Because the new data is like that:
This is because the fprint in my script does not add carriage return ('\r') at the end of the line. To add this, please use the following:
fprintf(fid2,'%s\r\n', str2{:});
By the way, if your data file contains numbers only, you can use dlmread and dlmwrite and do your task much easier, like:
x = dlmread('yourData.txt');
dlmwrite('test.txt',x(1:744),'newline','pc');
...only 2 lines!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Data Preparation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by