Search code examples
concatenationtrimjqstrip

jq: How to Catenate an Array and Strip Spaces


The following jq command (Windows) successfully catenates all the "text" properties into one string replacing any spaces with a single space albeit in a roundabout way. Almost correct. What I really want is to first replace any leading or trailing space in "text", then catenate all "text" properties. A difference being that embedded (non-leading, non-trailing) spaces must not be removed. How can this be done?

jq ".segments[].words | map(.text?) | join(\",\") | gsub(\"[ ]\"; \"\") | gsub(\"[,]\"; \" \")"

Solution

  • Consider:

    def trim: sub("^ *";"") | sub(" *$";"");
    

    Or you could simply use: gsub("^\s|\s*$";"")

    There are other ways to trim a string but the above should get you started.