-1

I want to count the occurences of a word in a file with only one line of code. Example: for the input: "hi, welcome to the himalaya. hihi" "hi" the output will be 4 (because the word "hi" occurs 4 times)

I tried using tr and grep, but it doesn't count "hihi" twice, but only once.

tr 'WORD' '\n' < $1 | grep $2 | wc -l

For the given example above, the output was 3 instead of 4. Thank you!

Aaron
  • 24,009
  • 2
  • 33
  • 57
GunTop
  • 3
  • 1
  • `grep -o "$2" "$1" | wc -l`? (if `$1` is a filename...) – Wiktor Stribiżew May 29 '19 at 09:26
  • 5
    Possible duplicate of [How can I count the occurrences of a string within a file?](https://stackoverflow.com/questions/6741967/how-can-i-count-the-occurrences-of-a-string-within-a-file). The exact answer is [here](https://stackoverflow.com/a/14510665/3832970). – Wiktor Stribiżew May 29 '19 at 09:30
  • `perl -nE 'BEGIN { $/ = shift } END { say $. - ($. && 1) }' "$2" "$1"`? – melpomene May 29 '19 at 09:30
  • @GunTop if `hihi` is 2 `hi`s then you aren't counting **words**, you're counting **strings**. Words are strings of word-consituent characters (typically alpha-numeric plus underscore) separated by non-word-constituent characters (punctuation, spaces, etc.). When counting **words** `hi` only appears once in the input `"hi, welcome to the himalaya. hihi"`. – Ed Morton May 29 '19 at 12:37
  • Thank you all, guys! you're awesome. I'll try these codes out! – GunTop May 30 '19 at 11:44

2 Answers2

0

try this:

grep -o "hi" input.txt | wc -l
UtLox
  • 3,744
  • 2
  • 10
  • 13
0

since you tagged the question with awk:

awk '{s+=gsub(/WORD/,1)}END{print s}' file

thus, a single process solution, also possible to be extended.

Kent
  • 189,393
  • 32
  • 233
  • 301