Skip to content

Instantly share code, notes, and snippets.

@lansana
Created August 18, 2017 11:41
Show Gist options
  • Save lansana/aa7518dd3671318384e73a4ea8e7098e to your computer and use it in GitHub Desktop.
Save lansana/aa7518dd3671318384e73a4ea8e7098e to your computer and use it in GitHub Desktop.
Bash script to find/replace a line in a file
#!/usr/bin/env bash
######################################################################################
# USAGE: bash bash/replace-line.sh "replace this line" "to this line" in-this-file.txt
######################################################################################
function escapeSlashes {
sed 's/\//\\\//g'
}
# replace-line.sh directory
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# First argument (old value)
OLD_LINE_PATTERN=$1
# Second argument (new value)
NEW_LINE=$2
# Third argument (file to replace text)
FILE=$3
# New value escaped (values may contain slashes; escape them).
NEW_VALUE=$(echo "${NEW_LINE}" | escapeSlashes)
cat "$FILE" | sed -e 's/'"$OLD_LINE_PATTERN"'/'"$NEW_VALUE"'/' > $DIR/temp.txt
mv $DIR/temp.txt "${FILE}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment