Solution using tr + sed + awk + sort (sed optional)


  • 0
    B

    Here's my solution:

    cat words.txt \
        | tr ' ' '\n' \
        | sed '/^\s*$/d' \
        | awk '{ words[$1]++ } END { for (key in words) print key, words[key] }' \
        | sort -rn -k2
    

    Cat the input
    Replace spaces with new line with tr
    Remove empty lines with sed
    Compute frequencies with awk
    Sort numerically using the second key with sort

    I could be using less utilities, but this way is more readable I feel. Just looked up the tr man page and there's a way to replace consecutive spaces with a single newline using the -s option. With UNIX utilities there is definitely more than one way to do it :)

    cat words.txt \
        | tr -s ' ' '\n' \
        | awk '{ words[$1]++ } END { for (key in words) print key, words[key] }' \
        | sort -rn -k2

Log in to reply
 

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