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

时间:2016-10-31 15:51:03

标签: 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文件,这些行按第一个值排序?

1 个答案:

答案 0 :(得分:2)

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

输入和输出文件的比较:

comparision

<强> P.S:
✶确保输入和输出文件都位于当前路径或提供完整路径,例如:&#39; D:\ Assignment \ InputFile.txt&#39;

✶我使用/复制了以下代码/想法:
https://stackoverflow.com/a/23357800/5698672
https://stackoverflow.com/a/5041474/3293881
https://stackoverflow.com/a/28348768/5698672
如果它能解决你的问题,那么也要对这些答案进行投票。