Search code examples
matlabappendtext-filesextract

Matab: copy certain rows from text files to another file


I have 300 files which have similar structure. I am interested in rows 82-nd and 90-th in each file.

The 82-nd row is:
span 1 = -0.193, 1.980

The 90-th row is:
span 9 = 0.000, 557.000

I would like to copy the last number from rows 82 and 90 next to each other, also append those values from each file, like so:

output-file:

1.980 557.000
2.568 687.500
1.158 496.030
............

Can someone help me? It would also be ok, if I could copy each 82 and 90 row to new file and the others under that, like so:

span 1 = -0.193, 1.980
span 9 = 0.000, 557.000

span 1 = -0.193, 2.568
span 9 = 0.000, 687.500

span 1 = -0.193, 1.158
span 9 = 0.000, 496.030
.....


Solution

  • We can use textscan with headerlines to jump to the desired rows.

    The format spec span %d = %f, %f tells textscan to give us the span id in {1} and span values in {2} and {3}. It assumes lines 82 and 90 are formatted strictly as described in the question (i.e., span x = y, z).

    This code scans 1 line twice (first at line 82, then at 90). Alternatively you could also scan 9 lines once (lines 82-90 in one go) and then index into those 9 lines.

    row1 = 82; % row of span 1
    row9 = 90; % row of span 9
    
    files = dir('/path/to/data/*.dat'); % change to real path
    result = nan(length(files), 2); % preallocate
    
    for file = files
        fpath = fullfile(file.folder, file.name);
        fid = fopen(fpath);
        
        format = 'span %d = %f, %f'; % assume `span x = y, z`
        lines = 1 % scan 1 line twice (we could also scan 9 lines at once and index the output)
        span1 = textscan(fid, format, lines, 'headerlines', row1 - 1);
        span9 = textscan(fid, format, lines, 'headerlines', row9 - row1);
        
        if (span1{1} == 1) && (span9{1} == 9) % verify span id
            result(1, :) = [span1{3} span9{3}];
        end
        
        fclose(fid);
    end
    
    csvwrite('result.csv', result);