Shell Scripting: Counting Files with a Specific Word in a Directory

Shell Scripting @ Freshers.in

Shell scripting is a versatile tool for automating tasks and performing operations on files and directories. In this article, we’ll delve into the creation of a shell script that accepts a directory name as an argument and counts the number of files within that directory containing a specific word. We’ll provide detailed insights into the script’s implementation, along with practical examples and outputs to demonstrate its effectiveness in file analysis and processing.

Understanding the Shell Script:

The shell script we’ll be developing will utilize Unix commands and shell scripting constructs to traverse the specified directory, search for files containing the specified word, and count the occurrences.

Script Implementation:

#!/bin/bash
# Check if directory name and word argument are provided
if [ $# -ne 2 ]; then
    echo "Usage: $0 <directory> <word>"
    exit 1
fi
# Assign directory name and word to variables
directory="$1"
word="$2"
# Check if the specified directory exists
if [ ! -d "$directory" ]; then
    echo "Error: Directory '$directory' not found."
    exit 1
fi
# Count files containing the specified word
count=$(grep -lr "$word" "$directory" | wc -l)
echo "Number of files containing the word '$word' in '$directory': $count"

Example:

Suppose we have a directory named “documents” containing text files with various content. We’ll execute the shell script with the directory name and a specific word as arguments to count the number of files containing that word.

$ ./count_files_with_word.sh documents example

Output:

Upon execution of the script, the number of files within the specified directory containing the specified word will be displayed.

Number of files containing the word 'example' in 'documents': 3
Author: user