リストにシリアル番号を割り当てる

リストにシリアル番号を割り当てる

次の行を含むファイルがあります。

   8 GeodeticCorrosiveness-4096     
   8 MetricalDrosky-4096            
   8 UncontrovertiblePhoebus-4096   
   9 FlabbyAutochthones-4096        
   9 UndispensedCreeds-4096         
   9 WaltonianAtomicities-4096      
  10 AtheismDuumvirate-4096         
  10 HeliocentricAllative-4096      
  10 HepaticPhaedra-4096            
  11 High-speedBuchan-4096       

私は次のようなものを作りたいと思います:

8   8 GeodeticCorrosiveness-4096     
8   8 MetricalDrosky-4096            
8   8 UncontrovertiblePhoebus-4096   
5   9 FlabbyAutochthones-4096        
5   9 UndispensedCreeds-4096         
5   9 WaltonianAtomicities-4096      
2  10 AtheismDuumvirate-4096         
2  10 HeliocentricAllative-4096      
2  10 HepaticPhaedra-4096            
1  11 High-speedBuchan-4096             

つまり、最初の列を基準に降順に並べ替えたときに、各行を順番に分類したのです。シェルスクリプトがこれを行うのに役立つことがUnixにありますか?

ベストアンサー1

sortこれは、以下を実行する短いawkスクリプトのように見えます。

$ sort -srn file.txt | awk '{if ($1 != prev) num=NR; print num, $0; prev=$1}' | sort -srn
8    8 GeodeticCorrosiveness-4096     
8    8 MetricalDrosky-4096            
8    8 UncontrovertiblePhoebus-4096   
5    9 FlabbyAutochthones-4096        
5    9 UndispensedCreeds-4096         
5    9 WaltonianAtomicities-4096      
2   10 AtheismDuumvirate-4096         
2   10 HeliocentricAllative-4096      
2   10 HepaticPhaedra-4096            
1   11 High-speedBuchan-4096  

どちらの呼び出しもsort最初にリストをソートして最後に反転しますが、awkスクリプトは最初のフィールドを表示して変更されたことを確認し、新しい値が表示された最後の行番号を印刷します。

おすすめ記事