My simple solution (one line with pipe)


  • 51
    S
    cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{ print $2, $1 }'
    

    tr -s: truncate the string with target string, but only remaining one instance (e.g. multiple whitespaces)

    sort: To make the same string successive so that uniq could count the same string fully and correctly.

    uniq -c: uniq is used to filter out the repeated lines which are successive, -c means counting

    sort -r: -r means sorting in descending order

    awk '{ print $2, $1 }': To format the output, see here.


  • 0
    L

    why I cannot use 'more'


  • 3
    S

    Good Code,But I don't use (sort uniq awk)

    #!/usr/bin/env bash
    
    declare -A HashWord
    File="words.txt"
    
    function ReadTxtFile
    {
        while read Line
        do
            Word=(${Line})
            for Var in ${Word[@]}
            do
                HashWord+=( [${Var}]='1')
                Word[${Var}]=
                for i in ${Word[@]}
                do
                    if [[ ${Var} == ${i} ]];then
                        Value=${HashWord[${Var}]}
                    fi
                done
    
            done
        done < ${File}
    
    
        for Key in ${!HashWord[*]}
        do
            echo "${Key} ${#HashWord[${Key}]}"
        done
    }
    
    
    ### Main Logic
    
    ReadTxtFile

  • 6
    G

    I think the second sort in your code should be followed with -nr, not just -r


  • 0
    Q

    cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -nrk 1 | awk '{ print $2, $1 }'


  • 0
    S
    This post is deleted!

  • 0
    S

    sed 's/ /\

    /g ' words.txt| sed '/^$/d' |sort |uniq -c | awk '{print $2,$1}'|sort -nr -k 2


  • 0
    M

    @GodForward You're right.


  • 1
    H

    Hi, there are some problems in your code. When you use 'sort -r', you need add '-n'.
    If you use yours to execute the follow example, you will know what I mean.

    '''
    how many cans can a canner can if a canner can can cans
    a canner can can as many cans as a canner can if a canner can can a can
    a canner can can as many cans as a canner can cans
    '''


  • 0
    E

    @shujia2112 This solution works only with Bash 4, right?


  • 0
    D

    @shujia2112
    去除掉下面的部分,程序依然正确
    Word[${Var}]=
    for i in ${Word[@]}
    do
    if [[ ${Var} == ${i} ]];then
    Value=${HashWord[${Var}]}
    fi
    done
    这部分的程序写了有什么用?


Log in to reply
 

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