Charles Kozlers Personal Website

Tag: count pattern matches in string

[Linux/Shell/Bash] Count pattern matches/instances in string

by Chuck Kozler on Jan.20, 2010, under Computers, Linux/Unix, Networks/Servers, Programming, Web Dev

This handy little Bash scripting function will count the number of instances it finds in a string by the given delimeter. As of right now, its pretty basic…I didnt go too far into expanding it and working it (like going through and escaping all character escapes) and only escape for | and \.

 
function countPatterns
{
	string_in="$1"
	delim="$2"
	if [ $delim == "/" ] || [ $delim == "|" ]; then 
		delim="\\$delim";
	fi
	retval=`echo $string_in | perl -ne 'while(/'${delim}'/g){++$count}; print "$count\n"'`
	return $retval
}

Remember, this isnt really completed but you get the idea. The use is something like:

countPatterns "this|is|a|string|" "|"
instances="$?"
 
#would output 4
echo $instances
Sphere: Related Content

Leave a Comment :, , , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...