JDY
JDY

Reputation: 167

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!

Upvotes: 1

Views: 172

Answers (2)

Will
Will

Reputation: 24709

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, respectively. 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 POSIX character classes as you mentioned in your post:

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

Upvotes: 6

Barmar
Barmar

Reputation: 781721

You need to use capture groups to copy the letter and number into the replacement.

perl -pe 's/([a-z])(\d)/$1, $2/i'

$1 and $2 are replaced with the parts of the original string that matched the patterns enclosed in parentheses.

Upvotes: 3

Related Questions