In linux bourne shell: how to count occurrences of a specific word in a file

By the way, I mean any line with space delimiters.

Suppose a file test.txthas the following words, marked with spaces:

hello hello hello hell osd
hello
hello 
hello
hellojames beroo helloooohellool axnber hello
way
how 

I want to count the number of times the word hello appears on each line.

I used the command awk -F "hello" '{print NF-1}' test.txtto show the number of occurrences of the word hello on each line:

3
1
1
1
4
0
0

Thus, he finds a total of 3 + 1 + 1 + 1 + 4 = 10 occurrences.

The problem is in the fourth line: hello only 1 time as a separate word; words such as hellojames and helloooohellool should not be counted because greeting is not limited to spaces.

So, I want him to find 7 occurrences of hello as a separate word.

, 7 ?

+3
7
awk '{ for(i=1; i<=NF; i++) if($i=="hello") c++ } END{ print c }' file.txt

:

awk '{ c=1; for(i=0; i<=NF; i++) if($i=="hello") c++; print c }'
+6
grep -o '\<hello\>' filename | wc -l

\< \> - , foohello hellobar.

awk -F '\\<hello\\>' ... .

+3

:

sed 's/\s\+/\n/g' test.txt | grep -w hello  | wc -l

:

sed 's/\s\+/\n/g' text.txt

, test.txt, . sed 's/FIND/REPLACE/g' FIND REPLACE , . \s\+ " ", \n - .

grep -w hello

, hello .

wc -l

.


If you want to count the number of occurrences per line, you can use the same technique, but process one line at a time:

while read line; do
  echo $line | sed 's/\s\+/\n/g' | grep -w hello  | wc -l
done < test.txt
+2
source
for word in `cat test.txt`; do
  if [[ ${word} == hello ]]; then
    helloCount=$(( ${helloCount} + 1));
  fi;
done;

echo ${helloCount} 
0
source
a=$(printf "\01")
b=hello
sed -e "s/\<$b\>/ $a /g" -e "s/[^$a]//g" -e "s/$a/ $b /g" file | wc -w
0
source
cat $FileName | tr '[\040]' '[\012]' | grep $word | wc -l

This command will change the space in a new line, then you can grep this word and count the number of lines containing this word.

0
source

Change the “needle” and “file”

#!/usr/bin/env sh

needle="|"
file="file_example.txt"

IFS=$'\n'

counter=0
for line in `cat $file`
do
    counter=$[$counter+1]
    echo $counter"|"`echo $line | grep -o "$needle" | wc -l`
done

It will print the line number and the number of occurrences separated by the channel symbol

0
source

All Articles