Reputation: 3838
I'm a noob at bash need to replace the mypassword
part of this line in a file
"rpc-password": mypassword
with mynewpassword
I tried
perl -pi -e "s,PASSWORD,${password},g" "${user_conf}"
but it dosen't seem to do anything :( I can use anything that will work inside a bash script, it dosen't have to be bash or perl.
Upvotes: 5
Views: 9971
Reputation: 67900
Using a loose regex without keeping backups is a bad idea. Especially if you intend to use dynamic replacement strings. While it may work just fine for something like "mypassword"
, it will break if someone tries to replace with the password "ass"
with "butt"
:
"rpc-password": mypassword
Would become:
"rpc-pbuttword": butt
The more automation you seek, the more strict you need the regex to be, IMO.
I would anchor the replacement part to the particular configuration line that you seek:
s/^\s*"rpc-password":\s*\K\Q$mypassword\E\s*$/$mynewpassword/
No /g
modifier, unless you intend to replace a password several times on the same line. \K
will preserve the characters before it. Using \s*
liberally will be a safeguard against user-edited configuration files where extra whitespace might have been added.
Also, importantly, you need to quote meta characters in the password. Otherwise a password such as t(foo)?
Will also match a single t
. In general, it will cause strange mismatches. This is why I added \Q...\E
(see perldoc perlre) to the regex, which will allow variable interpolation, but escape meta characters.
Upvotes: 6
Reputation: 25555
You can also use sed for this:
sed -i 's/mypassword/mynewpassword/g' file
Upvotes: 1