Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
fuss:awk [2017/12/25 11:33] – [Remove Duplicate Entries in File Without Sorting] officefuss:awk [2018/01/02 01:47] – [Convert Key-Value Map to JSON] office
Line 63: Line 63:
  
 will merge all the lines in a file by two. will merge all the lines in a file by two.
 +
 +====== Convert Key-Value Map to JSON ======
 +
 +Given an input such as:
 +<code>
 +a1 : "abc
 +c2  : def
 +e3 : "ghi "
 +f5 :" a     b"
 +</code>
 +
 +The following awk script:
 +<code bash>
 +awk -F: '
 +    function trim(s) { 
 +        return gensub(/^[ \t"]*|[ \t"]*$/, "", "g", s) 
 +    }
 +    BEGIN {
 +        printf "{"
 +    } 
 +    NR > 1 { 
 +        printf(", "
 +    } 
 +    { 
 +        printf("\"%s\":\"%s\"", trim($1), trim(substr($0, index($0,":") + 1)));
 +    }
 +    END {
 +        print "}"
 +    }
 +'
 +</code>
 +
 +will return the JSON object:
 +<code>
 +{"a1":"abc","c2":"def","e3":"ghi","f5":"    b"}
 +</code>
 +
 +where keys and values are trimmed for spaces and quotes from the start and end.
 +
 +[[iot/openhab2/templates/apc_ups|One example application]] would be creating a JSON object out of the status of an APC UPS:
 +<code bash>
 +apcaccess | awk -F: '
 +    function trim(s) { 
 +        return gensub(/^[ \t"]*|[ \t"]*$/, "", "g", s) 
 +    }
 +    BEGIN {
 +        printf "{"
 +    } 
 +    NR > 1 { 
 +        printf(", "
 +    } 
 +    { 
 +        printf("\"%s\":\"%s\"", trim($1), trim(substr($0, index($0,":") + 1)));
 +    }
 +    END {
 +        print "}"
 +    }
 +'
 +</code>
  

fuss/awk.txt · Last modified: 2022/04/19 08:28 by 127.0.0.1

Access website using Tor Access website using i2p Wizardry and Steamworks PGP Key


For the contact, copyright, license, warranty and privacy terms for the usage of this website please see the contact, license, privacy, copyright.