MATLAB Answers

How to trim a text file with start and end line numbers

23 ビュー (過去 30 日間)
Hello ,
I want to trim the data.txt file with the start and end line numbers,
for example,
start line number = 5
end line number =10
I want a new .txt file with the lines only between 5 and 10.
I have attached a model data.txt with this question. Can anyone help me ?
MATLAB R2015b
Regards,
Jaffrey Hudson

  0 件のコメント

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

採用された回答

Vismay Raj
Vismay Raj 2019 年 6 月 25 日
read the file using
filetext = fileread('file.txt')
split the text on newline and store the array of lines in a new variable
newstr = splitlines(filetext)
use start:end in array to display required elements
s = 5
e = 10
newArr = newstr(s:e)

  5 件のコメント

表示 2 件の古いコメント
Jaffrey Hudson Immanuel Jeyakumar
Jaffrey Hudson Immanuel Jeyakumar 2019 年 6 月 25 日
Yes. The newArr,
newArr =
[1x41 char] [1x41 char] [1x41 char] [1x41 char] [1x41 char] [1x41 char]
The values are stored correctly.
What is the command to write the newArr in a new text file ?
Jaffrey Hudson Immanuel Jeyakumar
Jaffrey Hudson Immanuel Jeyakumar 2019 年 6 月 25 日
Thank you.
I wrote like this,
fileID = fopen('exp.txt','w');
%fprintf(fileID,'%6s %12s\n','x','exp(x)');
fprintf(fileID,'%s',newArr);
fclose(fileID);
Can you pease correct my script ?

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

その他の回答 (1 件)

Pullak Barik
Pullak Barik 2019 年 6 月 25 日
I use the code-generator from the import tool to only import the lines needed from the text file, and then copied the cropped content to a new file.
% Auto-generated by MATLAB
% Setup the Import Options
opts = delimitedTextImportOptions("NumVariables", 1);
start_line_no = 5; %Change this variable to specify the starting point
end_line_no = 10; %Change this variable to specify the ending point
% Specify range and delimiter
opts.DataLines = [start_line_no, end_line_no];
opts.Delimiter = "!";
% Specify column names and types
opts.VariableTypes = "string";
opts = setvaropts(opts, 1, "WhitespaceRule", "preserve");
opts = setvaropts(opts, 1, "EmptyFieldRule", "auto");
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
% Import the data
test = readtable("C:\Users\pullak\Documents\MATLAB\data.txt", opts);
%Change the path above to point to your data.txt
% Convert to output type
test = table2array(test);
% Clear temporary variables
clear opts
%% Auto-generated code ends here
path = 'crop_data.txt';
%This stores the cropped data in the directory of the code script file, change the path as per your will
fid = fopen(path, 'w');
fprintf(fid, '%s\n', test{:});
fclose(fid);

  1 件のコメント

Jaffrey Hudson Immanuel Jeyakumar
Jaffrey Hudson Immanuel Jeyakumar 2019 年 6 月 25 日
Thank you for the alternative solution too.

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

製品


リリース

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by