Matlab command to access the last line of each file?

I have 20 text files, and I want to use the matlab loop to get the last line of each file without considering the other lines. is there any matlab command to solve this problem?

+5
source share
3 answers

One thing you can try is to open the text file as a binary file, find the end of the file and read individual characters (i.e. bytes) back from the end of the file. This code will read the characters from the end of the file until it presses the newline character (ignoring the newline if it finds it at the very end of the file):

fid = fopen('data.txt','r');     %# Open the file as a binary
lastLine = '';                   %# Initialize to empty
offset = 1;                      %# Offset from the end of file
fseek(fid,-offset,'eof');        %# Seek to the file end, minus the offset
newChar = fread(fid,1,'*char');  %# Read one character
while (~strcmp(newChar,char(10))) || (offset == 1)
  lastLine = [newChar lastLine];   %# Add the character to a string
  offset = offset+1;
  fseek(fid,-offset,'eof');        %# Seek to the file end, minus the offset
  newChar = fread(fid,1,'*char');  %# Read one character
end
fclose(fid);  %# Close the file
+5
source

On Unix, just use:

[status result] = system('tail -n 1 file.txt');
if isstrprop(result(end), 'cntrl'), result(end) = []; end

Windows tail GnuWin32 UnxUtils.

+3

It may not be very effective, but for short files it may be enough.

function pline = getLastTextLine(filepath)
fid = fopen(filepath);

while 1
    line = fgetl(fid);

    if ~ischar(line)
        break;
    end

    pline = line;
end
fclose(fid);
+2
source

All Articles