Skip to content

Instantly share code, notes, and snippets.

@andersonbosa
Last active April 11, 2024 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonbosa/9966c985fb5baf250271447746a714a3 to your computer and use it in GitHub Desktop.
Save andersonbosa/9966c985fb5baf250271447746a714a3 to your computer and use it in GitHub Desktop.
Bash function to replace a keyword with a provided value in a text file
#!/bin/bash
# Author: https://github.com/andersonbosa
# Source: https://gist.githubusercontent.com/andersonbosa/9966c985fb5baf250271447746a714a3/raw/31cba94a8db1acbeb3636e272e1345745c72891e/replace_keyword.sh
#
# Example usage:
# replace_keyword "example.txt" "{{title_template}}" "New Title"
#######################################
# Function to replace a keyword with a provided value in a text file
# Arguments:
# $1: File path of the text file
# $2: Keyword to be replaced
# $3: Value to replace the keyword with
# Returns:
# None
#######################################
replace_keyword() {
local file_path="$1"
local keyword="$2"
local keyword_value="$3"
# Check if the file exists
if [ ! -f "$file_path" ]; then
echo "Error: File $file_path not found."
return 1
fi
# Replace the keyword with the provided value using sed
sed -i "s/$keyword/$keyword_value/g" "$file_path"
echo "Keyword '$keyword' replaced with '$keyword_value' successfully in $file_path."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment