-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
pad function #2033
Comments
Maybe there could be a left pad (lpad) as above and a corresponding right pad (rpad) function. |
Any updates about this? |
How about something along this line? It's not recursive, but it's likely pretty fast. def lpad(string;len;fill):
if len == 0 then string else (fill * len)[0:len] + string end;
def rpad(string;len;fill):
if len == 0 then string else string + (fill * len)[0:len] end; |
If you want to pad string to make the result have the expected length, |
@davidfetter: those defs are not idiomatic. As in @itchyny's second example, it would be more idiomatic for the string to be presented as input to the filter. It would also be in keeping with jq to use
|
By the way what's the difference of |
Ahhhh, sorry, ignore my comment! It is different when |
Adjusted per comments, and thanks for looking at this! |
By the way it doesn't work for multi-width characters, if you really want to pad spaces to strings to make them fit to a fixed width in terminals (wrap text by a frame, for example). String length and displayed width are different things. |
OK! I 've seen a lot of options here jeje. Are we going to have a pad() function or similar in the next release of jq? Thanks! |
Add some performance tests: Testing 1000 times [def pad(n): if n==0 then (.) else "0" + (.) | pad(n - 1) end]
Testing 1000 times [def lpad(string;len;fill): if len == 0 then string else (fill * len)[0:len] + string end]:
|
Could it also handle multi-character fill strings? Then the fill multiplier would be (total_length - string_length) / fill_length, rounded up. As-is, it multiplies a multicharacter fill_string a lot more than it needs to before truncating it (e.g., if the fill-string is already long enough to handle the whole field width), but it still works just fine. Maybe it could accommodate for this if it were an internal function. |
Hi!
Can you consider to add a builtin pad(n) function to jq?
Something like this:
def pad(n): if n==0 then (.) else "0" + (.) | pad(n - 1) end;
Congratulations for this great tool!
The text was updated successfully, but these errors were encountered: