0

I've got a string h="aaaa bbb" which contains 2 spaces between aaaa and bbb,and I want to count the number of spaces in it.However,when I try

echo $h|grep -o ' '|wc -l

it shows 1 instead of the desired two. Is there any way not to treat consecutive spaces in string as one?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
novahow
  • 1
  • 1
  • `spaces_only=${h//[^[:space:]]/}; echo "${#spaces_only}"` counts total number of spaces, not number of *consecutive* spaces. But then, the OP's original code didn't filter for consecutive spaces either. – Charles Duffy Mar 28 '20 at 17:02
  • BTW, [BashPitfalls #14](http://mywiki.wooledge.org/BashPitfalls#echo_.24foo) is another relevant link re: the real/underlying problem (`echo $h` discarding spaces and having other undesirable side effects). – Charles Duffy Mar 28 '20 at 17:05

0 Answers0