Replace spaces with first character of the line on each line

Viewed 49

I have data that looks like this:

1, 100 200 3030 400 50023
2, 30 444 44334 441 123332
3, 100 200 3030 400 50023

I need to turn it into this:

1, 100
1, 200
1, 3030
1, 400
1, 50023
2, 30
2, 444
2, 44334
2, 441
2, 123332
etc.

I was able to do it with a vim macro but the data is far too. I was hoping something like awk could do it. But I am not really familiar with it.

Any help would be apperciated.

2 Answers
$ cat input
1, 100 200 3030 400 50023
2, 30 444 44334 441 123332
3, 100 200 3030 400 50023
$ awk '{for(i=2;i<=NF;i++) printf "%s %s\n", $1, $i}' input
1, 100
1, 200
1, 3030
1, 400
1, 50023
2, 30
2, 444
2, 44334
2, 441
2, 123332
3, 100
3, 200
3, 3030
3, 400
3, 50023
 awk -F',' '{split($2,a," "); for (i in a)  print $1, "," , a[i]}' 

explanation:

 awk -F',' -- Set field seprator as , 
'{split($2,a," "); -- Split column 2 using " "(space) as delimiter and populate array a 
for (i in a)  print $1, "," , a[i]} -- Loop to access all element of array' 

Demo :

 renegade@Renegade:~$ cat test.txt 
1, 100 200 3030 400 50023
2, 30 444 44334 441 123332
3, 100 200 3030 400 50023
renegade@Renegade:~$ awk -F',' '{split($2,a," "); for (i in a)  print $1, "," , a[i]}'  test.txt 
1 , 100
1 , 200
1 , 3030
1 , 400
1 , 50023
2 , 30
2 , 444
2 , 44334
2 , 441
2 , 123332
3 , 100
3 , 200
3 , 3030
3 , 400
3 , 50023
renegade@Renegade:~$ 
Related