1

I am trying to get a JSON key and change its property in the file using -i flag with sed. The issue is, I cannot get this regex right. It works perfectly fine for the simple replace case, but I cannot get it working using this regex. For simplicity, I have just tried a simple echo, rather than saving it to the file. Ideas?

 x=0.0.179     
 echo "version: 0.0.178" | sed 's/^[ ]*\"version\"[ ]*:[ ]*\"\([0-9]+\.[0-9]+\.[0-9]+\)\".*$/\$x/'
 0.0.178
Vlad Balanescu
  • 664
  • 5
  • 27
  • 3
    What's your JSON, what do you expect, and what do you actually get ? – Brian Agnew Mar 16 '17 at 11:09
  • 3
    If you're trying to edit JSON, there are tools for that (e.g. `jq`). An approach using sed is probably going to break at some point. – Tom Fenech Mar 16 '17 at 11:11
  • @brian I think the expectation is well explained in my question. I am expecting to get that 0.0.178 replaced by 0.0.179. I am only restricted to sed, so I cannot use jq. Is there a way I can do it with sed? – Vlad Balanescu Mar 16 '17 at 11:13
  • Is there a reason for not installing jq? Doesn't your server has Python installed? – hek2mgl Mar 16 '17 at 11:30

3 Answers3

2

Why should you be complicating it with sed, just do,

x="0.0.179"
echo "version: 0.0.178" | sed  "s/version: .*/version: $x/"
version: 0.0.179

and BTW if your JSON input can be parsed and modified via jq, go for it. Use this ONLY as a last resort.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    This is a pretty solid answer. Using sed with double quoted expressions is difficult if you include ANY backslashes in the expression. See http://stackoverflow.com/questions/2369314/why-does-sed-require-3-backslashes-for-a-regular-backslash for details. – D.Shawley Mar 16 '17 at 11:22
  • I completely agree: Using `"` in sed is bad practice. – moestly Mar 17 '17 at 15:05
1

I think your sed regexp is looking for the version number within double-quotes. Your input to sed above is not quoted as such, and hence doesn't get replaced (I'd expect your JSON to be double-quoted though, hence my interest above re. your real JSON input).

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

This works. Mention the 's around $x

echo "version: 0.0.178" | sed 's/^[ ]*\"version\"[ ]*:[ ]*\"\([0-9]+\.[0-9]+\.[0-9]+\)\".*$/\'$x'/'

Bash variables do not get replaced inside strings with '. Use " whenever possible to avoid this, or just concat your variable into the command as shown above.

moestly
  • 1,681
  • 15
  • 19