Skip to content

Text format

nntrn edited this page Sep 29, 2023 · 4 revisions

Human readable

Number

def h: tostring | [while(length>0; .[:-3]) | .[-3:]] | reverse | join(",");
def h($num): $num | h;

Filesize

def to_precision($p):
  . |tostring|split(".")
  | [.[0], (.[1]|split("")|.[0:($p|tonumber)]|join(""))]
  | join(".")
  | tonumber;

def humansize(bytes;$p):
  (bytes|tonumber) as $size |
  if   $size > 1073741824 then "\(($size/1073741824)|to_precision($p))G"
  elif $size > 1048576    then "\(($size/1048576)|to_precision($p))M"
  elif $size > 1024       then "\(($size/1024)|to_precision($p))K"
  else $size
  end;

def humansize(bytes): humansize(bytes;1);

Wrap Text

# ~/.jq/text.jq
def wrap_text($s):
  $s |  "* " + gsub("(?<a>[\\s\\S]{70,85}) "; .a + "\n  ";"m" );
$ STRING='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' 

$ echo "$STRING" | jq -Rr 'include "text"; wrap_text(.)'
* Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
  incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
  exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
  dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
  pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
  deserunt mollit anim id est laborum.

Smart quotes

Add quotes to text containing spaces

def smart_quotes($s): $s | if (test("[ ?]";"x")) then "\([39]|implode)\($s)\([39]|implode)" else $s end;
jq -r -n 'env | to_entries | map("\(.key)=\(smart_quotes(.value))") | join("\n")'
Clone this wiki locally