Home > Back-end >  How to create a key-value dictionary with awk
How to create a key-value dictionary with awk

Time:01-25

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:,

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

One that handles empty records in data:

$ awk '{
    printf "%s%s",(p==""?"":p),(p==""?"":(  i%2?": ":", "))  # controlled output
    p=$0                                                     # store record for next round
}
END {
    print p                                                  # last record special
}' file

Output:

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