I came upon a page that talks about tricking sed into doing what I want, but the problem is that I don't understand the document. It's too advanced (for me).
https://learnbyexample.github.io/sed-lookarounds/

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.