Last active
April 11, 2024 18:01
-
-
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
This file contains 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
#!/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