This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
fuss:awk [2017/02/22 18:30] – external edit 127.0.0.1 | fuss:awk [2018/01/02 01:47] – [Convert Key-Value Map to JSON] office | ||
---|---|---|---|
Line 44: | Line 44: | ||
</ | </ | ||
+ | ====== Merge Lines by Two in File ====== | ||
+ | |||
+ | Given a file with the contents: | ||
+ | < | ||
+ | Q: What is this? | ||
+ | A: This is a FAQ! | ||
+ | </ | ||
+ | |||
+ | and you would like to achieve: | ||
+ | < | ||
+ | Q: What is this? A: This is a FAQ! | ||
+ | </ | ||
+ | |||
+ | then the following '' | ||
+ | <code bash> | ||
+ | awk ' | ||
+ | </ | ||
+ | |||
+ | will merge all the lines in a file by two. | ||
+ | |||
+ | ====== Convert Key-Value Map to JSON ====== | ||
+ | |||
+ | Given an input such as: | ||
+ | < | ||
+ | a1 : "abc | ||
+ | c2 : def | ||
+ | e3 : "ghi " | ||
+ | f5 :" a | ||
+ | </ | ||
+ | |||
+ | The following awk script: | ||
+ | <code bash> | ||
+ | awk -F: ' | ||
+ | function trim(s) { | ||
+ | return gensub(/^[ \t" | ||
+ | } | ||
+ | BEGIN { | ||
+ | printf " | ||
+ | } | ||
+ | NR > 1 { | ||
+ | printf(", | ||
+ | } | ||
+ | { | ||
+ | printf(" | ||
+ | } | ||
+ | END { | ||
+ | print " | ||
+ | } | ||
+ | ' | ||
+ | </ | ||
+ | |||
+ | will return the JSON object: | ||
+ | < | ||
+ | {" | ||
+ | </ | ||
+ | |||
+ | where keys and values are trimmed for spaces and quotes from the start and end. | ||
+ | |||
+ | [[iot/ | ||
+ | <code bash> | ||
+ | apcaccess | awk -F: ' | ||
+ | function trim(s) { | ||
+ | return gensub(/^[ \t" | ||
+ | } | ||
+ | BEGIN { | ||
+ | printf " | ||
+ | } | ||
+ | NR > 1 { | ||
+ | printf(", | ||
+ | } | ||
+ | { | ||
+ | printf(" | ||
+ | } | ||
+ | END { | ||
+ | print " | ||
+ | } | ||
+ | ' | ||
+ | </ | ||