Andres Cabrera
Andres Cabrera

Reputation: 144

How to create a key-value dictionary with awk

I am trying to create a key-value dictionary with the following output

"a"
true
"b"
true
"c"
false

I try with thirst to put a colon after each value but it is not possible.

The format should be as follows:

"a": true, "b": true, "c": false

this is the command I am trying:

awk '{print $1":"$2","}'

and this is de fail output:

"a":, true:, "b":, true:, "c":, false:,

Upvotes: 1

Views: 1131

Answers (4)

RARE Kpop Manifesto
RARE Kpop Manifesto

Reputation: 2821

 mawk 'ORS = ORS < "&" && RS < ORS ? ", " : " : "' | 

 mawk 7 RS='[\7-/]+$'
"a" : true, "b" : true, "c" : false

Upvotes: 0

jhnc
jhnc

Reputation: 16762

Another simple awk solution:

awk -v ORS='' '
    NR>1 { print( NR%2 ? ", " : ": " ) }
    1;
    END { print "\n" }
' inputfile

The reason your code didn't work is that awk reads input a "record" at a time (by default, line by line). So your $2 is always empty.

Upvotes: 2

dawg
dawg

Reputation: 103874

You can use paste:

$ paste -sd':,' file
"a":true,"b":true,"c":false

Since paste only accepts input from a file, if you have a string, you would do:

$ paste -sd':,' <(echo "$your_str")

If you need the space after the , and : you can add them:

$ paste -sd':,' file | sed -E 's/([:,])/\1 /g'
"a": true, "b": true, "c": false

Or if you really want an awk:

$ awk  'NR%2{id=$1; next}
{s=s dlm id ": " $1; dlm=", "}
END{ print s }' file
"a": true, "b": true, "c": false

Upvotes: 3

markp-fuso
markp-fuso

Reputation: 34504

print $1":"$2"," references the 1st and 2nd fields from the current line, but you're requirement is to process fields from multiple lines, so you'll need to store the 1st line in a variable and then reference this variable when processing the 2nd line.

One awk idea:

awk '
NR % 2 { key=$1; next }                          # odd numbered line, save 1st field in variable "key"
       { printf sep key ": " $1; sep=", "}       # even numbered line, print key/value to stdout; sep is blank 1st time we reference it, and then we set it to ", " for all further references
END    { print "" }                              # terminate output line
' file

This generates:

"a": true, "b": true, "c": false

Upvotes: 0

Related Questions