Justin Justin - 6 months ago 11
Perl Question

Inserting a comma in between letter and number

I am a beginner to programming and had a quick question about regex matching and wanted to know if a quick solution existed in bash or perl to the following problem:

My file looks something like this.

Boy0.545, 35, 63, 75
Girl, 63, 723, 845, 45
Human13, 453, 634, 43


How would I insert a comma whenever a letter was followed DIRECTLY after by a number in each line? I was reading up on some regex and felt like something like this could work: /^[:alpha:][:digit:]$/ but am unsure how to continue. I would like to have

Boy, 0.545, 35, 63, 75
Girl, 63, 723, 845, 45
Human, 13, 453, 634, 43


Any help is appreciated. Apologies for the simple question! Thanks!

Answer

Try this:

$ cat testfile
Boy0.545, 35, 63, 75
Girl, 63, 723, 845, 45
Human13, 453, 634, 43

$ sed 's/\([A-Za-z]\)\([0-9]\)/\1, \2/g' testfile
Boy, 0.545, 35, 63, 75
Girl, 63, 723, 845, 45
Human, 13, 453, 634, 43

\([A-Za-z]\) and \([0-9]\) are capturing groups, which are referred to in the replacement section by \1 and \2. So we look for a number immediately following a letter, and replace it with the letter, then a comma, then a space, then the number.

You can also use character classes as you mentioned in your post:

sed 's/\([[:alpha:]]\)\([[:digit:]]\)/\1, \2/g' testfile