Shell Script: Extracting email addresses from a text file

Shell Scripting @

In this article, we’ll guide you through the process of creating a shell script for this purpose using common Unix utilities. We will explain each part of the script and provide a detailed example.┬áHere’s a shell script that takes a file name as an argument and extracts all the email addresses from it.

# Check if the user provided a file name as an argument.
if [ $# -ne 1 ]; then
    echo "Usage: $0 <file_name>"
    exit 1
# Get the file name from the command line argument.
# Check if the file exists.
if [ ! -f "$file_name" ]; then
    echo "Error: File '$file_name' not found."
    exit 1
# Use grep and a regular expression to extract email addresses.
grep -E -o -w "$email_pattern" "$file_name"

Script Explanation:

Shebang (#!/bin/bash): The first line tells the system to use the Bash interpreter to execute the script.

Argument Checking: The script checks if the user provided a single file name as an argument. If not, it displays a usage message and exits.

File Name Retrieval: It retrieves the file name from the command line argument.

File Existence Check: The script checks if the specified file exists. If not, it displays an error message and exits.

grep Command: The grep command is used with regular expressions (-E) to search for email addresses in the file.

-o: This option tells grep to only output the matching parts of each line.

-w: This option ensures that the match is a whole word (i.e., it doesn’t match email-like substrings within larger words).

Let’s assume you have a text file named emails.txt containing email addresses. To extract the email addresses from this file, you can use the script as follows:

bash emails.txt

Read more on Shell related articles

Author: user