Anyway, I finally found a solution, and it was with the help of AI... which of course probably just found this line from some website:
echo "$NUM" | sed -r ':a;s/^([-+]?[0-9]+)([0-9]{3})/\1,\2/;ta'
And I wrote the following enclosure:
# This function inserts commas into numbers at every 3 digits # and returns the result in a global variable called $STR. # function Commify { STR="$1" if [[ "$STR" =~ ([\+\-\$\(0-9\.]+) ]]; then local NEG='' local NUM="${BASH_REMATCH[1]}" local PREFIX="${STR%$NUM*}" local SUFFIX="${STR##*$NUM}" if [[ "$NUM" == *"+"* ]]; then NEG="+"; fi if [[ "$NUM" == *"-"* ]]; then NEG="-"; fi if [[ "$NUM" =~ 0+([1-9]+[0-9.]*) ]]; then NUM=${BASH_REMATCH[1]}; + fi NUM="$NEG$NUM" NUM=$(echo "$NUM" | sed -r ':a;s/^([-+]?[0-9]+)([0-9]{3})/\1,\2/;t +a') STR="$PREFIX$NUM$SUFFIX" fi }
I could possibly put this in a while loop and make it commify every number in a string, but I think this is fine as it is. Let's not overcomplicate things too much... Btw I can't help but wonder how amazingly similar Bash scripting is to Perl. There are soo many similarities!
In reply to Re^2: Commify function regex in Perl vs sed (off-topic sed)
by harangzsolt33
in thread Commify function regex in Perl vs sed
by harangzsolt33
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |