Created
August 18, 2017 11:41
-
-
Save lansana/aa7518dd3671318384e73a4ea8e7098e to your computer and use it in GitHub Desktop.
Bash script to find/replace a line in a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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