Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab command to access the last line of each file?

Tags:

file

matlab

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

like image 397
bzak Avatar asked Apr 17 '10 17:04

bzak


2 Answers

One thing you can try is to open the text file as a binary file, seek to the end of the file, and read single characters (i.e. bytes) backwards from the end of the file. This code will read characters from the end of the file until it hits a newline character (ignoring a 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
like image 74
gnovice Avatar answered Oct 13 '22 18:10

gnovice


On Unix, simply use:

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

On Windows, you can get the tail executable from the GnuWin32 or UnxUtils projects.

like image 27
Amro Avatar answered Oct 13 '22 18:10

Amro