How to replace specific contents in a file?

From the existing file, I need to replace specific contents possibly with var every time when the user changes the var.
e.g the contents in the file file.txt is 'My name is $n and I am $y years old' and every time user changed the var outside the file, the contents of the file should be created with the specific words updated.

Sounds like something sed could do.
Please show sample input file, and your desired outcome.

It's basically a file called db.txt:

dbname: database1
dbusername: samplename1
dbpwd: pwd1

The actual file is more complicated than this, so if someone else input database2, samplename2 and pwd2 from stdin, the db.txt file should change its contents to

dbname: database2
dbusername: samplename2
dbpwd: pwd2
$ cat db.sh

echo "dbname: $1"
echo "dbusername: $2"
echo "dbpwd: $3"

$ db.sh database2 samplename2 pwd2

Here is what I do for things like this firstly setup your template file with tags surrounded by "%%" eg:

dbname: %%DBNAME%%
dbusername:  %%DB_USER_NAME%%
dbpwd:  %%DB_PWD%%

Now set and export environment variables with the values you want and then call expand.sh:

DBNAME="testing1"; export DBNAME
DB_USER_NAME="Test user"; export DB_USER_NAME
DB_PWD="/home/testing1"; export DB_PWD
expand.sh mytemplate > template.expanded

expand.sh looks like this:

awk -F% ' /%%/ {
 while(match($0, "%%[A-Za-z0-9_]+%%")) {
    tmp = substr($0, 1, RSTART-1)
    var = substr($0, RSTART+2, RLENGTH-4);
    printf "%s%s", tmp, ENVIRON[var];
    $0=substr($0,RSTART+RLENGTH);
 }
 print; next } 1' $@