Federico Livi
Federico Livi

Reputation: 59

How to expand correctly a variable in sed command

I have this file:

user0:
  hash: $2a$12$DA47ZutoC.89KDePyBK.yubz.2vfEiLi28ENBRuyoNf.px3.vHINq
user1:
  hash: $2a$12$Auk82xqdbgFb4AJKyvSuWOKTQivuHhJZwckLii5/a5ILhCke0sddS
user3:
  hash: $2a$12$QW/dCK7CqE5s87OIk8QBeeBYVvD5tjbd46jH9wVD9YMWW31KQEA1y
user4:
  hash: $2a$12$60ds1ivJzM/DexIBYUilzO4BPjumsdTOETAHoopIxabffoWiDEkum

and a bash script to change the hash associated to a username. For example to change user1 hash, i would use:

sed -i "/user1:/{n;s,.*,  hash: NEW_HASH/}" MY_FILE

Now, in the script I have variables, and so actually my previous example is:

sed -i "/$1:/{n;s,.*,  hash: $hash/}" "$users"

My problem is that the $hash parameter has got also / characters, resulting in a sed error like this:

sed: -e expression #1, char 85: unterminated `s' command

How to correct my command in order to let it expand hash variable correctly? I tried some combinations of ' and " commands but without results. Any help? Thank you!

Upvotes: 0

Views: 145

Answers (1)

hek2mgl
hek2mgl

Reputation: 158250

Since you are using , as the delimiter for the s command it should be:

sed -i "/$1:/{n;s,.*,  hash: $hash,;}" "$users"
----------------------------------^ comma, not /

I've also appended a ; after the s command. Some implementations of sed need that.

Upvotes: 4

Related Questions