skip to Main Content

I have to update dictionary with new value for existing key in a JSON file.
I need no write new line after existing string using regex

Current file:

{
    "id": "aaaa",
    "desc": "Service aaa",
    "boss":"[email protected]",
    "email": [
        "[email protected]"
    ],

desired file:

{
    "id": "aaaa",
    "desc": "Service aaa",
    "boss":"[email protected]",
    "email": [
        "[email protected]"
        "[email protected]"
    ]

I have this ansible lineinfile module playbook, but I struggle with decent regex. Everything I try just adds new line in the very end of file.

---

- hosts: localhost
  gather_facts: no

  tasks:
  - name: insert line
    lineinfile:
     path: /home/file.json
     state: present
     insertafter:  " ^ "email": [ "
     line: '[email protected]'

How should I write correct regex in this case to write line after the string "email": [ ?

2

Answers


  1. Let’s say current file is aa.txt as follows

    {
        "id": "aaaa",
        "desc": "Service aaa",
        "boss":"[email protected]",
        "email": [
            "[email protected]"
        ],
    

    Use sed command

    sed '/"email.*[/!{p;d;};n;a new line' aa.txt
    

    Output

    {
        "id": "aaaa",
        "desc": "Service aaa",
        "boss":"[email protected]",
        "email": [
            "[email protected]"
    new line
        ],
    

    Alternatively use AWK

    awk '1;/"email.*[/{c=2}c&&!--c{print "new text"}' aa.txt 
    

    Output

    {
        "id": "aaaa",
        "desc": "Service aaa",
        "boss":"[email protected]",
        "email": [
            "[email protected]"
    new line
        ],
    
    Login or Signup to reply.
  2. quick comment :

    JSON spec mandates an ASCII comma (",") between values of arrays (plus your choice of whitespace(s)), so to make the proposed solutions compliant, they would have to resemble this instead

    —— (snippet directly from jq):

    {
      "id": "aaaa",
      "desc": "Service aaa",
      "boss": "[email protected]",
      "email": [
        "[email protected]",
        "newline"
      ]
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search