bash: How to create a key,value pairs from .txt file in linux
w | awk 'NR==1 {print $1}' >file.txt
cat file
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
lava1 pts/0 157.48.149.102 05:03 31.00s 0.31s 0.31s -bash
azureuse pts/1 157.48.149.102 07:26 0.00s 0.07s 0.05s w
From the above text file I want to create key,value pairs like json format as below is the expected output:
{
"USER" : "lava1",
"TTY" : "pts/1",
"FROM" : "157.47.49.254",
"LOGIN" : "12:32",
"IDLE" : "5.00s"
}
I'd suggest Miller for something like this - specifically, convert from "pretty print" to JSON:
$ mlr --ipprint --ojson cat file
{ "USER": "lava1", "TTY": "pts/0", "FROM": "157.48.149.102", "LOGIN@": "05:03", "IDLE": "31.00s", "JCPU": "0.31s", "PCPU": "0.31s", "WHAT": "-bash" }
{ "USER": "azureuse", "TTY": "pts/1", "FROM": "157.48.149.102", "LOGIN@": "07:26", "IDLE": "0.00s", "JCPU": "0.07s", "PCPU": "0.05s", "WHAT": "w" }
Selecting specific fields with cut
and renaming the LOGIN@
field:
$ mlr --ipprint --ojson cut -f USER,TTY,FROM,LOGIN@,IDLE then rename LOGIN@,LOGIN file
{ "USER": "lava1", "TTY": "pts/0", "FROM": "157.48.149.102", "LOGIN": "05:03", "IDLE": "31.00s" }
{ "USER": "azureuse", "TTY": "pts/1", "FROM": "157.48.149.102", "LOGIN": "07:26", "IDLE": "0.00s" }