Matlab 如何按第一个单词对文本文件的行进行排序?

Matlab 如何按第一个单词对文本文件的行进行排序?,matlab,Matlab,我有一个.txt文件,格式如下: 22 BLBL asas saaa212 x:12 y:123 66 BLadsBL asas saaa212 x:12 y:123 32 BLadsBL asas saaa212 x:13212 y:123 66 BLadsBL asas saaa212 x:1332 y:123 如何使用按第一个值排序的这些行创建一个新的.txt文件 inpfid = fopen('InputFile.txt'); %This .txt file contains the

我有一个.txt文件,格式如下:

22 BLBL asas saaa212 x:12 y:123
66 BLadsBL asas saaa212 x:12 y:123
32 BLadsBL asas saaa212 x:13212 y:123
66 BLadsBL asas saaa212 x:1332 y:123
如何使用按第一个值排序的这些行创建一个新的.txt文件

inpfid = fopen('InputFile.txt'); %This .txt file contains the data you gave in the question
allData = textscan(inpfid,'%s','Delimiter','\n');
% Read in the first word from each row of data
outcellarray = regexp(allData{:},'^([\w\-]+)','match');
% Store all the first numbers into a single cell array and sort them
[~, ind] = sort(str2double(vertcat(outcellarray{:})));
% Creating a cell with the required order
output = cellfun(@(x) x(ind), allData, 'UniformOutput', 0);
% Making it into a form useable for writing a text file
output= output{:}; 

outfid=fopen('OutputFile.txt','wt+'); %Creating an output file
for k = 1:length(output)-1
  %Writing the data
  fprintf(outfid,output{k});
  fprintf(outfid,'\n');
end
fprintf(outfid,output{end});
% You can loop from 1 to length(output) and skip the last line 
% but it'll append an extra line at the end of the output file
fclose(outfid); % Closing the output file
输入和输出文件的比较:


p.S:
✶ 确保输入和输出文件都位于当前路径,或提供完整路径,如:“D:\Assignment\InputFile.txt”

✶ 我使用/复制了以下代码/想法:




因此,如果这些答案能解决您的问题,请投票表决。

Ps我不在乎速度,只是未来最简单的代码,请避免用不相关的语言标记某些东西。是的,我这样做了,我保留了使用过的行的索引,只是一次又一次地运行文件,(并执行INTECPT)但这是非常丑陋的代码,我希望有人会给我一个更好的想法,我不想要一个代码只是一个正确的思考方式,你是如何阅读文件的?每一行都是一个字符串,还是将其拆分为不同的字段?它们是在一个数组、一个单元格数组、结构、表还是其他什么东西中?您想按第一个单词还是第一个值排序?e、 g.第一行是否按
22
BLBLBL
排序?您看过
排序
排序
了吗?