简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM