harangzsolt33 has asked for the wisdom of the Perl Monks concerning the following question:
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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Commify function regex in Perl vs sed (off-topic sed)
by LanX (Saint) on Sep 20, 2025 at 23:14 UTC | |
by harangzsolt33 (Deacon) on Sep 21, 2025 at 04:56 UTC | |
by LanX (Saint) on Sep 21, 2025 at 08:22 UTC | |
Re: Commify function regex in Perl vs sed
by eyepopslikeamosquito (Archbishop) on Sep 21, 2025 at 08:03 UTC | |
Re: Commify function regex in Perl vs sed
by sleet (Monk) on Sep 21, 2025 at 07:08 UTC | |
by LanX (Saint) on Sep 21, 2025 at 09:42 UTC |