Вопрос

I have strings of 32 chars in a file (multiple lines). What I want to do is to make a new file and put them there by making columns of 4 chars each.

For example I have:

00000000000FDAD000DFD00ASD00

00000000000FDAD000DFD00ASD00

00000000000FDAD000DFD00ASD00

....

and in the new file, I want them to appear like this:

0000 0000 000F DAD0 00DF D00A SD00

0000 0000 000F DAD0 00DF D00A SD00

Can you anybody help me? I am working for hours now and I can't find the solution.

Это было полезно?

Решение 2

Import

fid = fopen('test.txt');
txt = textscan(fid,'%s');
fclose(fid);

Transform into a M by 28 char array, transpose and reshape to have a 4 char block on each column. Then add to the bottom a row of blanks and reshape back. Store each line in a cell.

txt = reshape(char(txt{:})',4,[]);
txt = cellstr(reshape([txt; repmat(' ',1,size(txt,2))],35,[])')

Write each cell/line to new file

fid = fopen('test2.txt','w');
fprintf(fid,'%s\r\n',txt{:});
fclose(fid);

Другие советы

First, open the input file and read the lines as strings:

infid = fopen(infilename, 'r');
C = textscan(infid, '%s', 'delimiter', '');
fclose(infid);

Then use regexprep to split the string into space-delimited groups of 4 characters:

C = regexprep(C{:}, '(.{4})(?!$)', '$1 ');

Lastly, write the modified lines to the output file:

outfid = fopen(outfilename, 'w');
fprintf(outfid, '%s\n', C{:});
fclose(outfid);

Note that this solution is robust enough to work on lines of variable length.

Here's one way to do it in Matlab:

% read in file
fid = fopen('data10.txt');
data = textscan(fid,'%s');
fclose(fid);

% save new file
s = size(data{1});
newFid = fopen('newFile.txt','wt');
for t = 1:s(1) % format and save each row
    line = data{1}{t};
    newLine = '';
    index = 1;
    for k = 1:7 % seven sets of 4 characters
        count = 0;
        while count < 4
            newLine(end + 1) = line(index);
            index = index + 1;
            count = count + 1;
        end
        newLine(end + 1) = ' ';
    end
    fprintf(newFid, '%s\n', newLine);
end
fclose(newFid);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top