How can I titleize text (capitalize each word) with jq
?
Expected transformation: "lorum ipsum"
→ "Lorum Ipsum"
CodePudding user response:
this may be achieved with gsub
, ascii_upcase
, and named capture groups:
$ echo '"lorum ipsum"' | jq 'gsub("(?<x>[A-z])(?<y>[A-z] )"; "\(.x|ascii_upcase)\(.y)")'
"Lorum Ipsum"
CodePudding user response:
You can use nawk
for
loop, toupper
, sub
and substr
as below:
echo 'lorum ipsum' | nawk '{for(i=1;i<=NF;i )sub(/./,toupper(substr($i,1,1)),$i)}1'
CodePudding user response:
Given a string you consider calling a word, you may uppercase its first character by converting it into an array (./""
), modifying the first element (first|=ascii_upcase
) and joining all elements back together (add
) like so
./"" | first |= ascii_upcase | add
Similarly, given a string of words, split it into an array of words, apply the above to each element using map
and join them back together. Depending on what you (or the input data requires you to) consider a word, splitting the string might differ. Given your input example ("lorum ipsum"
), using a single space character as word separator will suffice. I'll set it in a variable (--arg ws ' '
) and use it for splitting (./$ws
) and joining (join($ws)
):
echo '"lorum ipsum"' | jq --arg ws ' ' '
./$ws | map(
./"" | first |= ascii_upcase | add
) | join($ws)
'