I've a csv file like below.
id,id1,id2,id3,id4,id5
1,101,102,103,104
2,201,202,203
3,301,302
Now what i want to add comma(,) to each line to make all line with same number of delimiters. So desired output should be.
id,id1,id2,id3,id4,id5
1,101,102,103,104,
2,201,202,203,,
3,301,302,,,
Using
awk -F "," ' { print NF-1 } ' file.csv | sort -r | head -1
I am able to find the max occurance of delimiter but not sure how to compare each line and append comma if its less than max.
With GNU awk (as I do not know if this works for other implementations)
$ # simply assign value to NF
$ awk -F, -v OFS=',' '{NF=6} 1' ip.txt
id,id1,id2,id3,id4,id5
1,101,102,103,104,
2,201,202,203,,
3,301,302,,,
If first line determines number of fields required:
$ awk -F, -v OFS=',' 'NR==1{f=NF} {NF=f} 1' ip.txt
id,id1,id2,id3,id4,id5
1,101,102,103,104,
2,201,202,203,,
3,301,302,,,
If any line determines max field:
$ cat ip.txt
id,id1,id2
1,101,102,103
2,201,202,203,204
3,301,302
$ awk -F, -v OFS=',' 'NR==FNR{f=(!f || NF>f) ? NF : f; next} {NF=f} 1' ip.txt ip.txt
id,id1,id2,,
1,101,102,103,
2,201,202,203,204
3,301,302,,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With