Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace every n'th occurrence in huge line in a loop

Tags:

linux

grep

sed

awk

I have this line for example:

1,2,3,4,5,6,7,8,9,10

I want to insert a newline (\n) every 2nd occurrence of "," (replace the 2nd, with newline) .

like image 893
ocra88 Avatar asked Nov 28 '22 14:11

ocra88


2 Answers

This might work for you (GNU sed):

sed 's/,/\n/2;P;D' file
like image 179
potong Avatar answered Dec 04 '22 05:12

potong


If I understand what you're trying to do correctly, then

echo '1,2,3,4,5,6,7,8,9,10' | sed 's/\([^,]*,[^,]*\),/\1\n/g'

seems like the most straightforward way. \([^,]*,[^,]*\) will capture 1,2, 3,4, and so forth, and the commas between them are replaced with newlines through the usual s///g. This will print

1,2
3,4
5,6
7,8
9,10
like image 36
Wintermute Avatar answered Dec 04 '22 04:12

Wintermute