I have a paragraph and I want to know which word appears the most at the beginning of a line from all paragraph

for example: paragraph:

Hello my name is X

Nice to meet you

Hello my name is Y

so Hello appears 2 times so i will output hello

awk -v RS= '
  {word = tolower($1); n = ++count[word]}
  n > max {max_word = word; max = n}
  END {print max_word}'
  • all my text is lowercase sorry! so what code now use?? – John B Apr 17 at 13:31
  • This code will work fine if the input is all lower case.  But, if you want to ‘optimize’ it, change word = tolower($1) to word = $1. – G-Man Apr 23 at 4:00

Below command will give you the required most repeated word along with the count.

cut -d ' ' -f1 file.txt | sort | uniq -c | head -1

Tried with below associate array method

awk 'NF{a[$1]++}END{for(x in a){print x" appears "a[x]}}' | sort -k3 -nr | sed -n '1p'


Hello appears 2

Why not easy part... awk '{ print $1 }' myfile |uniq -c

  • maybe you needed awk 'NF{ … }' infile| sort| uniq -c | sort -r|head -n1 | ... '? what you currently answered doesn't do anyting just adding 1 in front of each first word in a line. also single awk do the job then. – αғsнιη Apr 23 at 6:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.