How to write bash script to replace word with sed

Here’s a bash script to replace ‘10.11.12’ with ‘192.168.100’ in all .conf files:

#!/bin/bash

# Replace 10.11.12 with 192.168.100 in all .conf files
# Creates backup files with .bak extension

for file in ./*.conf; do
    if [ -f "$file" ]; then
        echo "Processing: $file"
        sed -i.bak 's/10\.11\.12/192.168.100/g' "$file"
    fi
done

echo "Replacement complete! Backup files created with .bak extension"

Alternative one-liner (without backups):

sed -i 's/10\.11\.12/192.168.100/g' ./*.conf

Alternative one-liner (with backups):

sed -i.bak 's/10\.11\.12/192.168.100/g' ./*.conf

Key points:

  • The dots in 10\.11\.12 are escaped with backslashes because . is a special character in regex (matches any character)
  • -i.bak creates backup files (e.g., bp-code120.conf.bak) before modifying
  • g flag replaces all occurrences on each line
  • The script processes all .conf files in the current directory

To use the script:

  1. Save it to a file (e.g., replace_ips.sh)
  2. Make it executable: chmod +x replace_ips.sh
  3. Run it: ./replace_ips.sh

The backup files allow you to revert if needed!

Leave a Reply