1

我有一个包含 json 项目列表的文件(每行一个),如下所示:

{ name: "Bob", location: "Boston, MA" }
{ name: "Peter", location: "San Francisco, CA" }
{ name: "Jane", location: "New York City, NY" }

假设,我想在 location 属性中替换MA为。Massachussetts我知道我可以使用sed 's/MA/Massachussetts',但这也将取代MAname领域的每一个。

有没有办法从命令行执行此操作jq,例如使用?

4

3 回答 3

3

在 jq (1.4) 的当前公共构建中,没有选择进行正则表达式替换。但是,这将在下一个版本中改变。

过滤器将允许您对字符串进行正则表达式替换。然后你可以做这样的事情:

.location |= sub("MA$"; "Massachussetts")

但是,您必须进行一些创造性的操作以允许多种选择。

于 2015-02-19T16:47:04.980 回答
1

你可以试试下面的。

$ sed 's/\(\blocation: \+"[^,]*, *\)MA"/\1Massachussetts"/g' file
{ name: "Bob", location: "Boston, Massachussetts" }
{ name: "Peter", location: "San Francisco, CA" }
{ name: "Jane", location: "New York City, NY" }

或者

$ sed 's/\(\blocation: \+"[^"]*\)\bMA/\1Massachussetts/g' file
{ name: "Bob", location: "Boston, Massachussetts" }
{ name: "Peter", location: "San Francisco, CA" }
{ name: "Jane", location: "New York City, NY" }
于 2015-02-19T10:02:22.443 回答
0

这是一个假设您的数据是干净的并且您需要的替换是有限的解决方案。

.location = (
   {
     "Boston, MA":        "Boston, Massachussettts",
     "San Francisco, CA": "San Francisco, California",
     "New York City, NY": "New York City, New York"
   }[.location] // .location
)

iffilter.jq包含上述过滤器并input.json包含

{ "name": "Bob", "location": "Boston, MA" }
{ "name": "Peter", "location": "San Francisco, CA" }
{ "name": "Jane", "location": "New York City, NY" }
{ "name": "Unknown", "location": "Unknown" }

然后

jq -M -c -f filter.jq input.json

会产生

{"name":"Bob","location":"Boston, Massachussettts"}
{"name":"Peter","location":"San Francisco, California"}
{"name":"Jane","location":"New York City, New York"}
{"name":"Unknown","location":"Unknown"}

如果查找失败,请注意使用//保持位置不变。

于 2017-08-24T19:37:49.247 回答