Solve this problem in linux style.


  • 0
    Z
    #!/bin/bash
     cat words.txt |tr  ' '  '\n'|sort|awk '{if($0!="")print}'|uniq -c|sort -nr|awk '{print $2,$1}'
    

    why use tr -nr not tr -r ?

    [root@pangu icai]# cat words.txt |tr  ' '  '\n'|sort |uniq -c|sort -r
          8 a
          7 canner
          5 cans
          4 as
          3 many
          2 if
          1 how
         13 can
    [root@pangu icai]# cat words.txt |tr  ' '  '\n'|sort |uniq -c|sort -nr
         13 can
          8 a
          7 canner
          5 cans
          4 as
          3 many
          2 if
          1 how
    

    why added awk '{if($0!="")print}' ?

    [root@pangu icai]# more words.txt 
    a  a   b
    [root@pangu icai]# cat words.txt |tr  ' '  '\n'|sort
    
    
    
    a
    a
    b
    [root@pangu icai]# cat words.txt |tr  ' '  '\n'|sort|awk '{if($0!="")print}'
    a
    a
    b
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.