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
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |