mikefarah / yq

yq is a portable command-line YAML, JSON, XML, CSV, TOML and properties processor
https://mikefarah.gitbook.io/yq/
MIT License
12.14k stars 595 forks source link

number/data formatting (e.g. padding) #2158

Open rriemann opened 1 month ago

rriemann commented 1 month ago

Please describe your feature request.

I use yq to split multi yaml documents into individual files with $index. I like to apply padding, so that I get:

Unfortunately, I have not found a method to add such zero padding. Exposing some strformat function (e.g. printf) would solve the problem.

Describe the solution you'd like If we have data1.yml like:

---
doc: 1
...
doc: 2

And we run a command:

yq -s '$index | printf("%03d")'

or

yq -s '$index | to_string("%03d")'

It could output:

One can pipe everything through an external program. Systems may have printf.

jstangroome commented 3 weeks ago

I needed this same capability and found a simple workaround for my scenario: splitting a many-document yaml into separate files, then later (after some processing) recombining the files into a single file again, but maintaining the order.

Using yq -s '$index' results in file names that sort incorrectly, e.g. [1, 10, 11, 2, 3, etc].

I know in advance I will only have less than one thousand documents, so I sum $index with the number 1000, e.g:

yq -s '1000 + $index`

And this produces file names that sort as desired, e.g. [1001, 1002, 1003, 1010, 1011, etc].

In my case the leading 1 has no negative impact on the final result so I tolerate it. Presumable a regex string substitution could remove it.