Home > Enterprise >  Regex for string starting with doueble quote and ending with [
Regex for string starting with doueble quote and ending with [

Time:12-17

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": [ ?

CodePudding user response:

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 '/".*\[/!{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;/".*\[/{c=2}c&&!--c{print "new text"}' aa.txt 

Output

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

CodePudding user response:

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"
  ]
} 
  • Related