Tag: grep pattern matches
[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