2016-10-31 13 views
-4

私はこの形式で.txtファイルがあります:最初の値でソートし、これらのラインで新しい.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 

を?入出力ファイルの

+0

私はスピードに気を使わず、最も単純なコード – JohnnyF

+0

将来的には、無関係の言語で何かをタグ付けしないでください。 –

+0

はい、私は、使用された行のインデックスを保持し、ファイルを何度も何度も実行していましたが(これはinteceptを実行しています)、これはrly醜いコードです。それについての正しい考え方 – JohnnyF

答えて

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


PS:
✶入力と出力の両方のファイルが現在のパスであること、それは確認してくださいまたは'D:¥Assignment¥InputFile.txt'のような完全なパスを提供してください。

✶私が使用した/からのコード/アイデアをコピー:
https://stackoverflow.com/a/23357800/5698672
https://stackoverflow.com/a/5041474/3293881
https://stackoverflow.com/a/28348768/5698672
だから、それはあなたの問題を解決しすぎた場合にこれらの答えに投票をあきらめます。

関連する問題