How can i read the line above a certain position?
2 次查看(过去 30 天)
显示 更早的评论
This is how the Nastran file looks like
$$ PSHELL Data
$
$HMNAME PROP 5101090"PSHELL_5101090" 4
$HWCOLOR PROP 5101090 44
PSHELL 510109096069002VAR0000696069002 96069002
$INSERT_PSHELL
I want to read the line above $INSERT_PSHELL. So i have ChatGPT part of this code written for me, which didn't work at all
function [PID, IDENT] = addPSHELL(inputDir, fileName, elementList)
%% function add exact many PSHELL properties as elements in element list
NumberToAdd = numel(elementList);
% Read the original file
fid = fopen(fullfile(inputDir, fileName), 'rt');
if fid == -1
error('Failed to open the file.');
end
% Move to the position where identifier is
while ~feof(fid)
line = fgetl(fid);
% Check if the line contains the identifier and move
if contains(line, '$INSERT_PSHELL')
IdentifierPosition = ftell(fid);
break;
end
end
% Read the last PSHELL to get PID
fseek(fid, IdentifierPosition, 'bof');
while ftell(fid) > 0
fseek(fid, -1, 'cof'); % Move back one byte
% Check if the previous byte is a newline character
if fread(fid, 1, 'char') == 10
break; % Found the line above
end
fseek(fid, -1, 'cof'); % Move back one more byte
end
lineAbove = fgetl(fid);
if ~(rem(length(lineAbove), 8) == 0)
error('the line above is not 8 multiples digit long')
end
% Break the line into 8-digit pieces
for i = 1:(length(lineAbove) \ 8)
lineAbove{i} = lineAbove(1+8*i : 8*i); % PSHELL PID MID1 T MID2 .....
end
0 个评论
采纳的回答
Joe Vinciguerra
2023-6-26
Replace "file_name" with whatever the name of your file is:
f = readlines(file_name); % read the file
k = find(f == "$INSERT_PSHELL"); % find the line number that matches your criteria
result = f(k-1); % this is the text on the line above it
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 PID Controller Tuning 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!