[英]Replace a line in a file with a string
I have a file file1
with the following content 我有一个文件
file1
,内容如下
{"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 我想查找包含单词
clio5
的行,然后用以下字符串替换找到的行
string='{"name":"clio5", "value":"1568688554"}'
$ 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. 根据@dogbane的评论更新了上述内容,因此即使文本包含
"
。如果文本可以包含":"
(带有适当的转义符),它仍然会失败,但这似乎极不可能,并且OP可以告诉我们是否一个有效的关注。
First you extract the name
part from your $string
as 首先,您从
$string
提取name
部分为
NAME=`echo $string | sed 's/[^:]*:"\([^"]*\).*/\1/'`
Then, use the $NAME
to replace the string as 然后,使用
$NAME
将字符串替换为
sed -i "/\<$NAME\>/s/.*/$string/" file1
Use awk like this: 这样使用awk:
awk -v str="$string" -F '[,{}:]+' '{
split(str, a);
if (a[3] ~ $3)
print str;
else print
}' file.json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.