Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell scripting - replace every 5 commas with a newline

Tags:

shell

unix

How can I replace every 5th comma in some input with a newline?

For example:

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15

becomes

1,2,3,4,5
6,7,8,9,10
11,12,13,14,15

Looking for a one-liner using something like sed...

like image 428
Jake Petroules Avatar asked Jan 18 '23 01:01

Jake Petroules


2 Answers

This should work:

sed 's/\(\([^,]*,\)\{4\}[^,]*\),/\1\n/g'

Example:

$ echo "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15" |
> sed 's/\(\([^,]*,\)\{4\}[^,]*\),/\1\n/g'
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
like image 156
Dennis Avatar answered Jan 21 '23 09:01

Dennis


This expression will do.

sed 's/\(\([0-9]\+,\)\{4\}\)\([0-9]\+\),/\1\3\n/g'

http://ideone.com/d4Va2

like image 36
Shiplu Mokaddim Avatar answered Jan 21 '23 08:01

Shiplu Mokaddim