I have a QNAP NAS with a modified Debian OS. The shell is using GNU bash, version 3.2.57(1)-release (x86_64-QNAP-linux-gnu). I have a number that I need to reformat to add thousand separators.
I used printf with the ‘.d parameter to set the thousands and forgot about % in CRON so I did something different and this works.
printf "This works $nl" | sed ':a;s/\B[0-9]{3}>/,&/;ta'
However, I now need to do further formatting on it by adding spaces to the front to make it easier reading. I have an input file with number that need format in thousand and also padded at the front.
12345 02-01-2024 root reallylongpasswordthatissecure
9999 01-01-2025 admin anotherreallylongpassword
300 01-01-2025 user 123456
I want the output file to convert all the lines, couple of dozen to
12,345 02-01-2024 root password
9,999 01-01-2025 admin password
300 01-01-2025 user 123456
I can’t feed in the sed line as that will convert any passwords as well if the password is something like 123456. So I want to convert the first column only to have thousand separators and front padding to 10 characters whilst leaving the rest.
I can get it to do the conversion for the thousand delimiters as above OR I can get it to do the padding with bash.
There must be a way to do this with sed. Sed looks like it can do it but is so complex that I have no idea how to do it.
I have played with sed to no avail.
I get
12,345 02-01-2024 root password
9,999 01-01-2025 admin password
300 01-01-2025 user 123456
OR
12345 02-01-2024 root password
9999 01-01-2025 admin password
300 01-01-2025 user 123456
I have written a bash script to extract the column and perform the conversion then simply append the rest on. That works fine but with the delimiters and padding it is 30 lines long and the rest of the script, the main part, is only six. It looks horribly inefficient and clumsy.
2
Answers
If you can use
awk
it is fairly easy:With your example, prints:
You can also use GNU sed:
Assumptions:
One
bash
idea using awhile/read
loop and aprintf
call:NOTES:
LC_ALL=en_US.UTF-8
depends on your default character seten_US.UTF-8
as neededThis generates: