Linux: replace a character with another after N occurances of a character with sed

We have the following scenario, we have a file with the following contents

aaa1,bbb1,ccc1,ddd1,aaa2,bbb2,ccc2,ddd2,aaa3,bbb3,ccc3,ddd3

We want to replace each fourth occurrence of comma “,” with a new line character, to do this:

$ sed 's/,/\n/4; P; D' example.txt
aaa1,bbb1,ccc1,ddd1
aaa2,bbb2,ccc2,ddd2
aaa3,bbb3,ccc3,ddd3

I hope you found this helpful :)

DevOps engineer, loves Linux, Python, cats and Amiga computers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store