I would like to right-align the amounts in a text using jq.
INPUT='
# comment
lorem ipsum
* Header
2022-01-01 Internet
provider 30.00 EUR
router 5.00 EUR
2022-01-01 House
rent 321.00 EUR
carports 20.00 EUR, 20.00 EUR
'
I came up with a solution, bit it looks a bit too lengthy for me - is there a more concise solution that avoids if-then-else
?
jq --raw-input --raw-output --argjson alignToColumn 40 '
"\\d+\\.?\\d*\\s+EUR" as $searchPattern |
if test($searchPattern)
then match($searchPattern) as $match |
sub($searchPattern;
" " * ($alignToColumn - $match.offset - $match.length) +
$match.string)
else .
end
' <<< "$INPUT"
Output
# comment
lorem ipsum
* Header
2022-01-01 Internet
provider 30.00 EUR
router 5.00 EUR
2022-01-01 House
rent 321.00 EUR
carports 20.00 EUR, 20.00 EUR
You can avoid if … then … else … end
by using the alternative operator //
.
"\\d+\\.?\\d*\\s+EUR" as $searchPattern | (match($searchPattern) as $m
| .[:$m.offset] + ($alignToColumn - $m.offset - $m.length) * " " + .[$m.offset:]
) // .
# comment
lorem ipsum
* Header
2022-01-01 Internet
provider 30.00 EUR
router 5.00 EUR
2022-01-01 House
rent 321.00 EUR
carports 20.00 EUR, 20.00 EUR