BASH

Read and Process File Line by Line

A bash script to efficiently read and process text files line by line, useful for parsing logs, configuration files, or lists of data for web development tasks.

#!/bin/bash

INPUT_FILE="list.txt"

# Check if the file exists
if [ ! -f "$INPUT_FILE" ]; then
    echo "Error: Input file '$INPUT_FILE' not found."
    exit 1
fi

echo "Processing file: $INPUT_FILE"

# Read the file line by line using a while loop and IFS
while IFS= read -r line;
do
    # Skip empty lines
    [[ -z "$line" ]] && continue

    # Example processing: echo the line and its length
    echo "Line: \"$line\" (Length: ${#line})"

    # Example: Perform an action based on line content
    if [[ "$line" == *"error"* ]]; then
        echo "  [ALERT] Error found in line!"
    fi
done < "$INPUT_FILE"

echo "File processing complete."
How it works: This script reads an input file line by line, assigning each line to the `line` variable. The `IFS=` prevents word splitting, and `-r` prevents backslash escapes from being interpreted. It demonstrates basic processing, such as skipping empty lines, echoing the line and its length, and conditionally performing actions based on line content. This pattern is ideal for parsing log files, configuration files, or processing lists of data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs