Shell – Use sed command to replace , appearing between numbers

scriptsedshellunix

I have a CSV file where data are in the following format

|001|,|abc,def|,123456,789,|aaa|,|bbb|,444,555,666

I want to replace only those "," that appears between numbers with some other character like say SOH or $ or *

other "," appearing in the line should not get replaced i.e. to say I wish to have following output

|001|,|abc,def|,123456*789,|aaa|,|bbb|,444*555*666

Can someone please help me with sed command pattern to get the above desired output

Best Answer

Try this

sed 's/\([0-9]\),\(-\?[0-9]\)/\1\*\2/g'

The first section matches a digit followed by a comma followed by a digit or a -. The next section simply regurgitates the first digit, the replacement character, and then the last digit.

This will catch any pattern like "#,#" or "#,-#", including some that may not be desired (e.g. "abc123,-def" --> "abc123*-def"). Fixing this requires more knowledge of the input stream. (see the comments for details.)

Related Question