How to get the no of matched occurrences using grep command in linux? - linux

If we use grep -c option it will give you the each occurrences only once per line. But I need the total no of matched occurrences not line count.

Use this
grep -o pattern path | wc -l

You can use -o flag to output only the matched part and then pipe it to wc -w to get word count.
Eg: ls ~ | grep -o pattern | wc -w

Related

Count specific pattern inside text

I have a huge file I want to use as shell command to count the number of the word 'new' in the file
a tried to use wc and grep but I get the number of lines that contain pattern only
From #Fravadona's suggestion:
grep -ow new file.txt | wc -l
-o means "print only the matches, one per line"
-w means "only match if it's a full word" and avoid matching for e.g. newOrder
wc -l counts the amount of lines grep did output

grep a character/word from a string and count number of occurrences in Linux

I like to a grep a character from a string then count it, I don't see from google search. Please advise. I might miss search for it.
node_count=`echo "test1|test2|test3" | grep "|" |wc -l`|echo $node_count
output is always 1 to me.
1
Remember that I don't grep from a file but a line of string. Grep from a file is easy.
You might want to use option -o of grep:
$ node_count=`echo "test1|test2|test3" | grep "|" -o |wc -l` && echo $node_count
# 2

Counting lines starting with a symbol

There are many lines containing the > symbol in a file. How can I count the total number of > symbols in a file? I have tried sed and grep and it did not work.
You can use GNU grep together with wc
grep -o '>' file.txt | wc -l
grep -o prints every match on a separate line. wc counts the lines.
Btw, it's not 100% clear in your question if the > can appear only at the start of a line. If you just want to count the lines that start with a > you can use the following grep command:
grep -c '^[[:space:]]*>' file.txt
^ matches the beginning of the line, [[:space:]]* allows for zero ore more space characters in front of the >, just in case.

grep the word if matching with condition

I have 2 words "staticed2f.css" and staticec3f.css . The bold char do change offen. I want to grep these words matching 'static' using grep command or any other script
Thank you
Try this,
grep -o \static[a-zA-Z0-9]*\.css
To change with other word,
var="otherword"
grep -o \(static\|$var)[\-a-zA-Z0-9.]*\.(css|js)

Counting lines starting with a certain word

How to count the number of lines in a text file starting with a certain word?
I do not want to use sed and then wc -l. Any better solution?
Just grep your word and then use wc -l to count the lines... like this
grep '^your_word' /path/to/file | wc -l
Try this:-
awk '/^yourwordtofind/{a++}END{print a}' file
grep -c "pattern" <filename>
For example: If you want to search for a pattern more in a file test.txt, then below is the command:
grep -c "more" test.txt
cat <filename> | grep <word> | wc -l

Resources