I don't know where to post this question as it's somewhat off-topic. But 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. So, I'm about to give up.

I saw a regex here on PerlMonks awhile back that took a string and inserts commas into numbers. It's pretty amazing how that works, and I am just now beginning to grasp why and how it works. But now I would like to port it to bash. Now, of course, bash doesn't have regex search and replace but sed does. So, when I plugged this into sed, it complains and says "sed: -e expression #1, char 39: Invalid preceding regular expression" (I'm using sed GNU v4.9 and bash 5.2.15 x64)

WHAT IS WRONG???

Original perl code: #!/usr/bin/perl -w use strict; use warnings; # I copied this regex from: # www.PerlMonks.org/?node_id=157725 # Usage: STRING = Commify(STRING) # sub Commify { defined $_[0] or return ''; my $N = reverse $_[0]; $N =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g; return scalar reverse $N; } print Commify('Testing 1234 testing... -123456789.01234567800 testing +test 4,500,000.00000');

And now the BASH script:

#!/bin/bash # This function inserts commas into numbers # at every 3 digits and returns the result # in a global variable called $STR. # function Commify { # First, reverse the string STR=$(echo "$1" | rev) STR=$(echo "$STR" | sed -E 's/([0-9]{3})(?=[0-9])(?![0-9]*\.)/\1,/g' +) # Now reverse it back: STR=$(echo "$STR" | rev) } Commify 'Testing 1234 testing... -123456789.01234567800 testing test 4 +,500,000.00000' echo $STR

In reply to 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.