Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking within a string

Status
Not open for further replies.

idiotboy

Programmer
Apr 20, 2001
21
GB
Hi,

I have a string e.g.

idiotboy|is|trying|to|count|how|many|pipes|are|in|this|string|

How can I count how many pipes there are in the string?

grep only returns the string itself

I can
While read pipe|;do tr -s "|" "|\n" $pipe|wc -l;done
but I thought there might be another way which is perhaps more efficient?

Thanks in advance.

Chris
 
Here's two possible ways...
[tt] echo $pipe | awk '{print gsub("\|","")}'[/tt]
...or...
[tt] echo $pipe | tr -dc '|' | wc -c[/tt]
 
Homework? Not for at least 20 years.

Thanks to both of you. I was a bit surprised that there isn't a more elegant solution.

As I proposed, my method works, I just wondered if it could be done better.

Thanks for the help and the link to the post.

Cheers,

Chris

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top