#!/bin/bash # A script to replace text_a with text_b in a file and report the changes. # # Usage: ./replace_and_report.sh "text_a" "text_b" # Check if the correct number of arguments are provided if [ "$#" -ne 3 ]; then echo "Error: Incorrect number of arguments." echo "Usage: $0 \"text_a\" \"text_b\"" exit 1 fi FILE="$1" TEXT_A="$2" TEXT_B="$3" # Check if the file exists if [ ! -f "$FILE" ]; then echo "Error: File '$FILE' not found." exit 1 fi echo "Searching for '$TEXT_A' in '$FILE' and replacing it with '$TEXT_B'..." echo "---" # Use `grep` to find the line numbers where TEXT_A exists # The output is a list of line numbers LINE_NUMBERS=$(grep -n "$TEXT_A" "$FILE" | cut -d: -f1) # Check if any matches were found if [ -z "$LINE_NUMBERS" ]; then echo "No occurrences of '$TEXT_A' found. No replacements made." exit 0 fi # Loop through each line number where a replacement will be made for line_number in $LINE_NUMBERS; do # Get the original line content before the replacement original_line=$(sed -n "${line_number}p" "$FILE") # Perform the replacement using `sed` on the specific line sed -i "${line_number}s/${TEXT_A}/${TEXT_B}/g" "$FILE" # Get the new line content after the replacement new_line=$(sed -n "${line_number}p" "$FILE") echo "Line $line_number:" echo " - Original: $original_line" echo " - New: $new_line" echo "---" done echo "Replacements complete. Changes saved to '$FILE'."