in reply to Re: Commify function regex in Perl vs sed (off-topic sed)
in thread Commify function regex in Perl vs sed

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!

Replies are listed 'Best First'.
Re^3: Commify function regex in Perl vs sed (off-topic sed)
by LanX (Saint) on Sep 21, 2025 at 08:22 UTC
    > just found this line from some website:

    > echo "$NUM" | sed -r ':a;s/^([-+]?[0-9]+)([0-9]{3})/\1,\2/;ta'

    IMHO not the same thing, but if you're happy... 🤷🏻‍♂️

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery