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

采纳的回答

Joe Vinciguerra
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 个)

类别

Help CenterFile Exchange 中查找有关 Text Data Preparation 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by