#!/bin/bash # Given a filename, a regex pattern to match and a replacement string: # If found, perform replacement, else append file w/replacement on new line. grep $2 $1 >/dev/null if [ $? -eq 0 ]; then # Pattern found; replace in file sed -i "s/$2/$3/g" $1 >/dev/null else # Not found; append on new line (silently) echo $3 | sudo tee -a $1 >/dev/null fi