AndrewS
AndrewS

Reputation: 177

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.

Upvotes: 0

Views: 1650

Answers (1)

Ulises Rosas-Puchuri
Ulises Rosas-Puchuri

Reputation: 1970

You might want to use option -o of grep:

$ node_count=`echo "test1|test2|test3" | grep  "|" -o |wc -l` && echo $node_count
# 2

Upvotes: 3

Related Questions