sed 将 url 中的 * 替换为 json 文件中的文本

sed replace * in url with text in json file

我想更改 json 文件中的键值

示例:

"House":"sample.house.city"

需要将“示例”一词更改为其他名称。

我可以这样做:

sed -i 's|sample.house.city|town-home.house.city|g' file.json

但不能保证“样本”每次都相同。

我试过:

sed -i 's|*.house.city|town-home.house.city|g' file.json

但它没有改变。

也尝试过:

sed -i 's|"*.house.city"|"town-home.house.city"|g' file.json

但结果是这样的:

"sample"town-home.house.city"

关于如何正确执行此操作的任何建议?

要匹配任何单词,可以使用[[:alnum:]_]* (POSIX BRE) / [[:alnum:]_]+ (POSIX ERE):

sed -i 's|[[:alnum:]_]*\.house\.city|townhome.house.city|g' file.json

查看 online demo:

#!/bin/bash
s='"House":"sample.house.city"'
sed 's|[[:alnum:]_]*\.house\.city|townhome.house.city|g' <<< "$s"

输出:

"House":"townhome.house.city"

请注意,您还需要转义用于匹配文字点的点。

Explanation

  • 1st Capturing Group (\w+)

    • \w matches any word character (equivalent to [a-zA-Z0-9_])
    • + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
  • 2nd Capturing Group (.house.city)

    • \. matches the character .
    • house matches the characters house literally (case sensitive)
    • \. matches the character .
    • city matches the characters city literally (case sensitive)
  • Global pattern flags

    • g modifier: global. All matches (don't return after first match)
  • replace with the 2nd Captured Group (.house.city)


$ sed -E 's/(\w+)(\.house\.city)/town-home/g' <<< '"House":"sample.house.city"'

"House":"town-home.house.city"

$ sed -iE 's/(\w+)(\.house\.city)/town-home/g' file.json