Use sed to strip the spaces, one line solution with explain


  • 2
    T

    sed 's/^\s+//g; s/\s+/ /g; s/\s+$//g' words.txt | tr ' ' '\n' | sort | uniq -c | sort -nr | awk -F' ' '{print $2" "$1}'

    1. use sed to strip head & tail spaces,and change inline spaces to one space
    2. use tr to trans space to return (these two steps also can be done cat words.txt | tr -s ' ' '\n')
    3. sort the words
    4. uniq to count words
    5. sort the stats result,-n for numeric sort,-r for reverse
    6. use awk to format the output

  • 0
    9
    tr -s " " "\n" < words.txt | sort | uniq -c | sort -nr -k1 | awk '{print $2,$1}'

Log in to reply
 

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