0

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.

AndrewS
  • 177
  • 5
  • 21
  • Expected behavior. Run the test without the *`wc`*. One line is output *`test1|test2|test3`* but it contains two pipe symbols. – jww Feb 17 '19 at 20:05
  • Thanks. so how can I achieve to get number of "|" in this example? the pipe between testx are just example but it can be ; or other special char, the outcome is same – AndrewS Feb 17 '19 at 20:07
  • *`echo "test1|test2|test3" | grep -o "|" | wc -l`*. Also see [Count total number of occurrences using grep](https://unix.stackexchange.com/q/6979/56041), [Count number of occurrences of a pattern in a file](https://stackoverflow.com/q/2908757/608639) and friends. – jww Feb 17 '19 at 20:09
  • You are good! Appreciate! I did not see that link. Sorry. I missed -L – AndrewS Feb 17 '19 at 20:10
  • Thanks, jww. I will search more carefully next time. Thanks. – AndrewS Feb 17 '19 at 20:16

1 Answers1

3

You might want to use option -o of grep:

$ node_count=`echo "test1|test2|test3" | grep  "|" -o |wc -l` && echo $node_count
# 2
Ulises Rosas-Puchuri
  • 1,900
  • 10
  • 12
  • I did this way | grep -o "|" |wc -l`|echo $node_count but I should echo $node_count on second line. Darn. Thanks again – AndrewS Feb 17 '19 at 20:13