in reply to Commify function regex in Perl vs sed

> I don't know where to post this question as it's somewhat off-topic

certainly not a PM discussion, I moved it to SOPW and marked it as off-topic.

> WHAT IS WRONG???

The trick in Formatting numbers with commas is to reverse the string of numbers to operate from right to left and to use positive and negative look-aheads

Regarding SED: to my knowledge are neither look-ahead nor look-behind supported.

This

> "sed: -e expression #1, char 39: Invalid preceding regular expression"

should have been obvious.

The normal recommendation when sed fails is to use Perl instead. (yes seriously)

> I am trying to figure this out and AI wasn't able to help me. And I have tried to fool with this for hours to no use.

which proves the current wisdom that LLMs are only useful when used by someone with more expertise in the matter. (no insult intended¹)

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

¹) but LOL²

²) SCNR in your case :-)

Replies are listed 'Best First'.
Re^2: Commify function regex in Perl vs sed (off-topic sed)
by harangzsolt33 (Deacon) on Sep 21, 2025 at 04:56 UTC
    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!

      > 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