Home > Software design >  Bash pattern matching or regex inside while loop for extracting and enriching data (from json to cmd
Bash pattern matching or regex inside while loop for extracting and enriching data (from json to cmd

Time:09-15

I have data in .json like this

[
 "items": 
    [
         {
            "dateAdd": "2019-06-21 13:48:22",
            "status": "Disconnected",
            "name": "PLVM32",
            "lastKeepAlive": "2022-07-14 14:10:21",
            "id": "972"
         },
         {
            "dateAdd": "2019-06-21 13:48:23",
            "status": "Never connected",
            "name": "PLVN50",
            "id": "973"
         },
         {
            "dateAdd": "2019-03-05 09:24:04",
            "status": "Active",
            "name": "PWVEAC",
            "lastKeepAlive": "2022-09-12 04:21:09",
            "id": "009"
       }
    ]
]  

then I have a script like this, read line by line, when if[[ $line == $nameCheck ]] is true, pause for a while, then do a check one line below the matching line,

if the condition if[[ a == lastKeepCheck ]] is true, then the value of $lastKeepCheck is printed to the console directly, otherwise what is printed to the console is NULL

#!/bin/bash

file="/root/agentDisconnect.json"

nameCheck="name"
lastKeepCheck="lastKeepAlive"

while IFS= read -r line
do
   if [[ $line == nameCheck ]]; then
       a=$line 1
      if[[ a == lastKeepCheck ]]; then
          echo "$a";
   else
      echo "NULL"
done < "$file"

the result to be displayed in the console is as follows:

 [root@PLVWZHUTD201 ~]#./script.sh
     2022-07-14 14:10:21
     NULL
     2022-09-12 04:21:09

how should my script be correct to run properly?

CodePudding user response:

To process JSON, use a JSON-aware tool:

jq -r '.items[] | .lastKeepAlive | .//="NULL"' $file
  •  Tags:  
  • bash
  • Related