Shell Script To Search and Count A Single Word Pattern Recursively In A UNIX File

in Categories Academic, File-management last updated June 28, 2008

Write a shell script that searches for a single word pattern recursively in the current working directory and display the numbers of times it occurred. This script also demonstrate how to search directory (current working directory) for all words or given pattern using grep command.

#!/bin/bash
# Search UNIX file / Linux file for a pattern recursively
# -------------------------------------------------------------------------
# Copyright (c) 2007 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
echo -n "Enter a one word pattern : "
read pattern
# word / name search using grep and count 
COUNT=$(grep -wr "${pattern}" . 2> /dev/null | wc -l)
echo "${pattern} occured ${COUNT} times."

Share this on: