views:

49

answers:

3

I have file like this which contains 5 columns. But some rows in my file have 4 columns by mistake, for example in this file at the 5th and 6th rows, you can see that the second column is missing. I want to replace the missing 2nd column with a blank space without disturbing other rows in my file with field separator ",".

11111,5323,6296,29-May-2010,1
22222,5323,6296,24-May-2010,1
33333,5323,6296,24-Jun-2010,1
44444,5323,6296,24-Jun-2010,1
55555,8061,15-Jul-2010,1
66666,6296,29-May-2010,1
77777,5323,6296,29-May-2010,1
88888,6296,29-May-2010,1
99999,6296,27-May-2010,1
10101,5323,6296,29-May-2010,1

Output that I need.

11111,5323,6296,29-May-2010,1
22222,5323,6296,24-May-2010,1
33333,5323,6296,24-Jun-2010,1
44444,5323,6296,24-Jun-2010,1
55555,,8061,15-Jul-2010,1
66666,,6296,29-May-2010,1
77777,5323,6296,29-May-2010,1
88888,,6296,29-May-2010,1
99999,,6296,27-May-2010,1
10101,5323,6296,29-May-2010,1
+1  A: 

Hello!

BEGIN{
    FS=","
}

NF==5 { print; }
NF==4 { printf("%s,,%s,%s,%s\n", $1, $2, $3, $4); }
Benoit
Thanks Benoit.. it works great..
gyrous
A: 

Using Vim I'd enter the following line in Ex-Mode: :%s/^(\d+),(\d+,\d+-\w+-\d+,\d)$/\1, ,\2/g

Ingmar Drewing
Could be a good solution, provided all lines follow this format. But you have to specify \v (verymagic) to have magic operate (because parentheses and + should otherwise be escaped)
Benoit
Ah, right - I see.
Ingmar Drewing
+1  A: 

shorter way

awk -F"," 'NF<5{sub(",",",,")}1' file
ghostdog74
The `-F","` is unnecessary.
Dennis Williamson
@Dennis: It is needed for the computation of `NF`.
schot
facepalm! [ ](http://google.com)
Dennis Williamson