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 theexpected output:

{ "USER" : "lava1", "TTY" : "pts/1", "FROM" : "157.47.49.254", "LOGIN" : "12:32", "IDLE" : "5.00s"
}
3

2 Answers

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" }

Since you want to produce JSON, let's use

w \
| tail -n +3 \
| jq -R '. | split("\\s+"; "g") | {USER:.[0], TTY:.[1], FROM:.[2], LOGIN:.[3], IDLE:.[4]}'

I'm using tail to skip the first 2 lines of w output.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like