bash - How to replace a pattern in script using sed in-place inside the script -


below test script in try replace 1 of line in script during runtime.

/home/xxx/test.sh

#!/bin/bash script_path=`pwd`/`basename $0` username=admin password='pass1234'  u="$(grep 'username' $script_path | awk -f'=' '{ print $2 }')" p="$(grep 'password' $script_path | awk -f'=' '{ print $2 }')"  sed -i "s/user=/user="${u}"/3" "$script_path" sed -i "s/pass=/pass="${p}"/3" $script_path  user= pass= 

issue: sed replacing search pattern here. tried "3" @ end hoping target 3rd occurance in file, didn't working expected.

i want to replace last user= , pass= user=admin , pass='pass1234'

any advice. still trying.

output expect file should changed to:

#!/bin/bash script_path=`pwd`/`basename $0` username=admin password='pass1234'  u="$(grep 'username' $script_path | awk -f'=' '{ print $2 }')" p="$(grep 'password' $script_path | awk -f'=' '{ print $2 }')"  sed -i "s/user=/user="${u}"/3" "$script_path" sed -i "s/pass=/pass="${p}"/3" $script_path  user=admin pass='pass1234' 

you should use grep -m 1 first match of username , password. , can use ^user= , ^pass= match lines want change:

#!/bin/bash script_path=`pwd`/`basename $0` username=admin password='pass1234'  u="$(grep -m 1 'username' $script_path | awk -f'=' '{ print $2 }')" p="$(grep -m 1 'password' $script_path | awk -f'=' '{ print $2 }')"  sed -i "s/^user=/user="${u}"/" "$script_path" sed -i "s/^pass=/pass="${p}"/" "$script_path"  user= pass= 

output is:

#!/bin/bash script_path=`pwd`/`basename $0` username=admin password='pass1234'  u="$(grep -m 1 'username' $script_path | awk -f'=' '{ print $2 }')" p="$(grep -m 1 'password' $script_path | awk -f'=' '{ print $2 }')"  sed -i "s/^user=/user="${u}"/" "$script_path" sed -i "s/^pass=/pass="${p}"/" "$script_path"  user=admin pass='pass1234' 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -