Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add index when same column value

I have this two columns file :

ctg0F     chr_1
ctg1F     chr_2
ctg2F     chr_3
ctg3F     chr_4
ctg4F     chr_5
ctg5F     chr_6
ctg6F     chr_4
ctg7F     chr_7
ctg8F     chr_8

The first column has different values. I’d like to add an index only for the repeated values in the second column. Here chr4 appears twice, and so :

ctg0F     chr_1
ctg1F     chr_2
ctg2F     chr_3
ctg3F     chr_4_1
ctg4F     chr_5
ctg5F     chr_6
ctg6F     chr_4_2
ctg7F     chr_7
ctg8F     chr_8

I do this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

awk '{ if (++count[$2]>1) print $1,$2"_"count[$2]; else print $1,$2"_"count[$2]}' 

But this even adds index "_1" for the unique values.

Any help?

>Solution :

$ awk '
    NR==FNR { tot[$2]++; next }
    { print $0 (tot[$2]>1 ? "_" (++cnt[$2]) : "") }
' file file
ctg0F     chr_1
ctg1F     chr_2
ctg2F     chr_3
ctg3F     chr_4_1
ctg4F     chr_5
ctg5F     chr_6
ctg6F     chr_4_2
ctg7F     chr_7
ctg8F     chr_8
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading