MOHAMED
MOHAMED

Reputation: 43518

Replace a line in a file with a string

I have a file file1 with the following content

{"name":"clio5", "value":"13"}
{"name":"citroen_c4", "value":"23"}
{"name":"citroen_c3", "value":"12"}
{"name":"golf4", "value":"16"}
{"name":"golf3", "value":"8"}

I want to look for the line which contains the word clio5 and then replace the found line by the following string

string='{"name":"clio5", "value":"1568688554"}'

Upvotes: 1

Views: 233

Answers (3)

anubhava
anubhava

Reputation: 784928

Use awk like this:

awk -v str="$string" -F '[,{}:]+' '{
  split(str, a);
  if (a[3] ~ $3)
     print str;
  else print
}' file.json

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203169

$ string='{"name":"clio5", "value":"1568688554"}'
$ awk -F'"(:|, *)"' -v string="$string" 'BEGIN{split(string,s)} {print ($2==s[2]?string:$0)}' file
{"name":"clio5", "value":"1568688554"}
{"name":"citroen_c4", "value":"23"}
{"name":"citroen_c3", "value":"12"}
{"name":"golf4", "value":"16"}
{"name":"golf3", "value":"8"}

$ string='{"name":"citroen_c3", "value":"1568688554"}'
$ awk -F'"(:|, *)"' -v string="$string" 'BEGIN{split(string,s)} {print ($2==s[2]?string:$0)}' file
{"name":"clio5", "value":"13"}
{"name":"citroen_c4", "value":"23"}
{"name":"citroen_c3", "value":"1568688554"}
{"name":"golf4", "value":"16"}
{"name":"golf3", "value":"8"}

Updated the above based on @dogbane's comment so it will work even if the text contains "s. It will still fail if the text can contain ":" (with appropriate escapes) but that seems highly unlikely and the OP can tell us if it's a valid concern.

Upvotes: 3

unxnut
unxnut

Reputation: 8839

First you extract the name part from your $string as

NAME=`echo $string | sed 's/[^:]*:"\([^"]*\).*/\1/'`

Then, use the $NAME to replace the string as

sed -i "/\<$NAME\>/s/.*/$string/" file1

Upvotes: 2

Related Questions